.NET Tips and Tricks

Blog archive

Returning Server-Side Errors from AJAX Calls

In ASP.NET MVC if you call an action method on the server from JavaScript code and that action method raises an exception, you'll get an error at the client that lets you know something has gone wrong. Unfortunately, all the information you typically get is the HTTP 500 error status code and it's default message.

If you want to get your own custom error message delivered to the client, you could create your own custom error object and return it from the server when something goes wrong. Unfortunately, with that solution jQuery won't call the error function you specified in your $.ajax call -- you'll have to write your own code to check if the object returned from the server is your error object .

A better solution is to instantiate and return your own HttpStatusCodeResult, which does cause jQuery to call the error function you specify in your $.ajax call. This server-side code will do the trick, while providing a custom message to go down to the client:

return new HttpStatusCodeResult(410, "Unable to find customer.")

On the client, your message will be in the third parameter passed to your error function.

If you're handling multiple error conditions in the same action method and need to take different actions at the client depending on the error, you can give each error a different status code. If so, in your client code you'll need to check the error status code to see what error has triggered your error function. The error code is returned in the status property of the first parameter passed to your error method.

This client-side example calls a server-side method and, if the method returns a 410 error, displays my custom error message to the user:

$.ajax({url:'/home/deleteCustomer',
  data: {id: "A123"),
  success: function (result) {//handle successful execution},
  error: function (xhr, httpStatusMessage, customErrorMessage) {
    if (xhr.status === 410) {
      alert(customErrorMessage);}}});

Here's the list of defined HTTP status codes. If your message is suggesting that the error is something that the user can fix, then you should probably pick a code from the 400 series (that series is reserved for client errors). Personally, I don't think developers are using status code 418 ("I'm a teapot") enough.

Posted by Peter Vogel on 10/07/2015


comments powered by Disqus

Featured

Subscribe on YouTube