Suppose I have a method in my controller that is called via a jQuery AJAX call. E.g. I'd like to delete a user. When everything goes fine, I return new Content('ok') and exit the method.
What should I do when an error occured? I'd like to indicate it by an appropriate status code, so that my error call back would be called called. Why status code? Read here: How do you trigger the "error" callback in a jQuery AJAX call using ASP.NET MVC?
However, the approach doesn't work because IIS7 returns it's own message (Bad request) insted of my custom error message.
Besides that there are two other catches:
The error callback could look like this: error: function(request) { alert(request.responseText);}
The best way to bubble that error from the server side (using php) to the client side is to send a header through the Ajax request somewhere in the 400's (which is always associated with errors). Once the Ajax request receives this it will trigger your error function.
Example: We are going to see how to use AJAX fail() methods to handle the error in the HTTP requests. The fail() callback takes 3 parameters where the first parameter is a JSON error object, the second parameter is given a reason in text format and the last parameter is for the error thrown by the HTTP request.
Setting the Response.StatusCode is the correct thing to do. To fix IIS's "helpful" error handling, set the HttpResponse.TrySkipIisCustomErrors property. You can read more about this here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With