Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should asp.net(mvc) server return error to jquery ajax call to be caught in error callback?

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:

  1. It has to work with IIS6 as well
  2. IE8 doesn't return the 'Bad request' string. Inside error callback the property request.responseTest is null.

The error callback could look like this: error: function(request) { alert(request.responseText);}

like image 765
stej Avatar asked May 19 '09 12:05

stej


People also ask

How can AJAX call error be resolved?

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.

How can we handle exception handling in Ajax?

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.


1 Answers

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.

like image 67
Craig Stuntz Avatar answered Sep 21 '22 23:09

Craig Stuntz