Reputation: 41442
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) {
}
});
Upvotes: 31
Views: 25847
Reputation: 35505
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.
Upvotes: 22
Reputation: 248
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/
Upvotes: 1
Reputation: 5574
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);
}
Upvotes: 8
Reputation: 17272
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.
Upvotes: 8
Reputation: 78104
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");
Upvotes: 1