31

This is related to my question on how to handle errors from jQuery AJAX calls. Several responses suggested that I use the "error" callback to display any errors from a jQuery AJAX call. I was wondering how to do that using ASP.NET MVC. Is there a way for my controller action to return an error that would be accessible from the "error" callback? The client side code would look something like this:

$.ajax({
   type: "POST",
   url: "MyUrl",
   data: "val1=test",
   success: function(result){
        // Do stuff
   },
   error: function(request,status,errorThrown) {

   }
 });

6 Answers 6

22

NOTE: Hey, this was posted before ASP.Net MVC even hit 1.0, and I haven't even looked at the framework since then. You should probably stop upvoting this.


Do something like this:

Response.StatusCode = (int)HttpStatusCode.BadRequest;
actionResult = this.Content("Error message here");

The status code should change depending on the nature of the error; generally, 4xx for user-generated problems and 5xx for server-side problems.

Sign up to request clarification or add additional context in comments.

1 Comment

Have you tried it in IE8? The request.responseText property contains null, there is not the 'Error message here' string :(
8

If you're using

[HandleError]

then throwing a HttpException is going to get caught and routed to your custom error page.

Another option is to use

Response.StatusCode = 500;
Response.Write("Error Message");
Response.End();

There's probably a more convenient way to write this but I haven't stumbled upon it yet.

3 Comments

Yeah, the [HandleError] attribute was what was getting me. It was catching my exceptions and redirecting to my error page. Unfortunately this attribute was on the controller class so I didn't see it immediately.
I believe you marked an incorrect answer. I would favor ALassek's answer over the HttpException which is technically wrong.
Does this work in all browsers? This to me would seem to be the more correct answer...
8

If you're using MVC 3, then you can return an ActionResult in your controller that has the HTTP status code and status message together:

return new HttpStatusCodeResult(500, "Error message");

Then, in your error callback:

error: function (request, textStatus, errorThrown) {
    alert(request.statusText);
}

4 Comments

I wonder what the code is behind new HttpStatusCodeResult(500, "Error message"); is. Is the source someplace or maybe we can reflector it? Probably be helpful for those of us in 2.
@rball - The code is on codeplex at the following link: aspnet.codeplex.com/releases/view/50092
That takes me to the entire source. Not sure if I clicked on the wrong thing, but even just casually sifting through the source didn't find anything. I'll have to download and see if I can find it through the IDE.
+1 for the HttpStatusCodeResult() object... but "Error message" is never returned to the browser.
1

According to this page, you just need to apply the header HTTP/1.0 500 Internal Server Error on your ASP.net page. The $.ajax request will catch that error and execute the error callback function. =]

Comments

1

I think that event is raised for any response that has a response code other than 200. I can't find proof of this in the docs though.

To do this from code (works in Webforms):

throw new HttpException(500, "Error message");

4 Comments

How do you send a response code other than 200 from a controller action though? Let's say my controller action determines that the user doesn't have the right to access the function and I want to return a response code other than 200 so that the "error" callback is hit. How would I do this?
Hmm, would throwing an exception from the controller action do the trick? That should send back a 500 response code right?
Edited the answer to provide a possible way of doing it
I think maybe this answer combined with Todd's first way would be the complete way to do this.
1

I send you a proposal; works with contrelled and uncontrolled exceptions.

  public class CodeExceptionToHttpFilter : FilterAttribute, IExceptionFilter
{
    public CodeExceptionToHttpFilter()
    {
      Order = 2;
    }
    public void OnException(ExceptionContext filterContext)
    {
      var codeException = filterContext.Exception as CodeException;
      var response = filterContext.RequestContext.HttpContext.Response;
  response.StatusCode = (codeException == null)? 550: 551;
      response.ContentType = MediaTypeNames.Text.Plain;
      response.Charset = "utf-8";
      response.Write(filter.Exception.Message);
      filterContext.ExceptionHandled = true;
      response.TrySkipIisCustomErrors = true;
   }

}

More info on my blog. http://rodrigopb.wordpress.com/2012/11/28/gestion-de-errores-en-peticiones-ajax-a-mvc/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.