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) {

   }
 });
Community
  • 1
  • 1
Kevin Pang
  • 41,172
  • 38
  • 121
  • 173

6 Answers6

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.

Adam Lassek
  • 35,156
  • 14
  • 91
  • 107
  • 1
    Have you tried it in IE8? The request.responseText property contains null, there is not the 'Error message here' string :( – stej May 19 '09 at 12:50
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);
}
Derek Morrison
  • 5,456
  • 4
  • 31
  • 24
  • 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 Sep 29 '10 at 22:09
  • @rball - The code is on codeplex at the following link: http://aspnet.codeplex.com/releases/view/50092 – amurra Sep 30 '10 at 00:57
  • 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. – rball Oct 01 '10 at 16:58
  • +1 for the HttpStatusCodeResult() object... but "Error message" is [never returned to the browser](http://weblogs.asp.net/gunnarpeipman/archive/2010/07/28/asp-net-mvc-3-creating-httpstatuscoderesult-with-view-based-body.aspx). – Zephyr was a Friend of Mine Oct 04 '11 at 20:09
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.

Todd Smith
  • 17,084
  • 11
  • 59
  • 78
  • 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. – Kevin Pang Jan 02 '09 at 19:15
  • I believe you marked an incorrect answer. I would favor ALassek's answer over the HttpException which is technically wrong. – Todd Smith Jan 02 '09 at 19:26
  • Does this work in all browsers? This to me would seem to be the more correct answer... – rball Oct 02 '09 at 15:55
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/

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");
John Sheehan
  • 77,456
  • 30
  • 160
  • 194
  • 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? – Kevin Pang Jan 02 '09 at 18:46
  • Hmm, would throwing an exception from the controller action do the trick? That should send back a 500 response code right? – Kevin Pang Jan 02 '09 at 18:48
  • Edited the answer to provide a possible way of doing it – John Sheehan Jan 02 '09 at 18:51
  • I think maybe this answer combined with Todd's first way would be the complete way to do this. – rball Oct 02 '09 at 15:56
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. =]

Salty
  • 6,688
  • 3
  • 33
  • 31