ASP.NET MVC 5 Web API + jQuery AJAX – Exception Handling
ASP.NET MVC 5 Web API – Restful public class GraphController : ApiController { … … public JObject Post(JObject obj) { … … if (type != null && typeid != null) … … else throw new Exception("Node Type / Node ID is invalid."); } } If there is no Specific Definition from Web API Controller, the Response Code is 200 for Normal Status & the Response Code is 500 for Exception Case. The Response Code can be captured from Browser Development Tools – Network Tab during AJAX HttpRequest. jQuery AJAX function can also be captured the Response Code to perform different Condition Development. |
JavaScript – jQuery AJAX ( may be fired from OnLoad Event & OnClick Event. ) $("#exception").hide(); $("#networkblock").html(""); $.ajax({ url: "/api/Graph", data: { type: "Person", typeid: 2 }, /* Either One of Property is null. The Exception would be thrown from Restful Server Side. */ type: "POST", success: function (data) { … … }, error: function (e) { $("#exception").show(); $("#exception").html(JSON.parse(e.responseText).Message + " – " + JSON.parse(e.responseText).ExceptionMessage); } }); |