Handling Exceptions using jQuery and ASP.NET MVC
[tweetmeme style=”compact”] Using AJAX has become one of the de facto practices in many web based RIAs. The use of jQuery is on the rise in many web applications, especially the ones built using ASP.NET MVC. Making AJAX calls using jQuery is quick and easy. A typical web request can have an expected response or an exception. It is therefore important to catch exceptions when we make any AJAX calls so that we can show some message which makes sense to the user.
Lets begin with our Controller. Create the following method to throw JSON version of the exception.
private JsonResult ThrowJSONError(Exception e) { Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest; //Log your exception return Json(new { Message = e.Message}); }
Specifying the StatusCode as HttpStatusCode.BadRequest or HttpStatusCode.InternalServerError or simply 500 will let the javascript know that there is something wrong in the response.
Lets create an ActionMethod to throw an exception which we will catch using jQuery.
public ActionResult DivideByZero() { try { throw new DivideByZeroException(); } catch (DivideByZeroException e) { return ThrowJSONError(e); } }
The above method will throw a DivideByZeroException which will be converted to a JSON string in the catch block and returned to the caller. Lets write the jQuery code to call the ActionMethod.
$(document).ready(function() { $.ajax({ type: "GET", url: "AJAX/DivideByZero", dataType: "json", success: function(data) { if (data) { alert("Success!!!"); } }, error: function(xhr, status, error) { DisplayError(xhr); } }); }); function DisplayError(xhr) { var msg = JSON.parse(xhr.responseText); alert(msg.Message); }
Here we are making a call to the DivideByZero ActionMethod. Obviously the exception will be thrown,which will be caught in the error block. The responseText is a string of serialized data, which will not be useful unless we parse it to JSON. We can use the native JSON parser available in the latest browser. But, this as I found out is not helpful in IE 7 or lower. Fortunately, there is a useful library at JSON.org that can parse the responseText to JSON.
Let me know if there are better ways of handling exceptions in jQuery.
Hope you found it useful!
Hi, nice concept, however there’s no need for json parsing in this case, use the Request.StatusDescription for the message, and write the stacktrace to the response.
error: function(xhr) {
xhr.statusText; //Error.Message
xhr.responseText;//StackTrace
xhr.status;//Numeric Error Status
}
You can even override the default handleerror attribute to check if Request.IsAjaxRequest() is true, then write the response as explained above.
HTH,
Erik
Thanks Erik,
If the param xhr is not parsed as JSON then value of xhr.statusText will be undefined as xhr is treated as a string and not JSON. Hence the JSON parser was required. Let me know if I misunderstood.
Thanks for dropping by 🙂
Cheers,
Sumit
Hey again Sumit,
I meant that you don’t need to write it as JSON on the server side, since you can access it as attributes of the xhr.
I’m working on a small demo that’ll show what I meant=, will post a comment with the link as soon as it’s ready.
Cheers,
Erik
i use this technique as well, and for actions marked as Ajax only, i have a [JSonExceptionCapture] attribute so i don’t have to duplicate exception handling code in my actions.
Hey again Sumit, here’s the demo : http://demos.erikzaadi.com/mvc/ErrorsForAjax/
There’s a download link for the source at the site..
Please note that this does not play well when not running from IIS, AKA via the Visual Studio Debugger.
Cheers,
Erik
Hey Eric,
Nice stuff! Its lot better than what I’ve done.
Thanks for sharing 🙂
Cheers,
Sumit
hi Erik,
Can you repost the link. It seems to be dead
[…] to Vote[FriendFeed] Handling Exceptions using jQuery and ASP.NET MVC 2LeggedSpider (12/22/2009)Tuesday, December 22, 2009 from […]
If you are returning the stacktrace to the user you are doing it wrong.
This is a classic example of something @bellware likes to describe as “geek autism”.
By all means catch the error, then log it somewhere and return a clean error message to the user indicating the action failed.
Neal,
I completely agree with you. Stacktrace should NEVER be returned to the user. I should not have added the same in the article as it gives a wrong picture. I have removed it.
The approach that you had mentioned is the ideal one and is the one followed by me as well. The intention in the article was to show that we can return our own custom JSON in our catch block when an exception occurs.
Thanks for sharing your views 🙂
Cheers,
Sumit
nice tutorial. Thanks for sharing.
Thanks Rana 🙂
Thanks for the code guys. One question though: how do i distinguish between the error that is a caught exception (thrown in the web service) and AJax error inside the error block?
Is there a a error.status or some other variables I should check for that? I am now working on the error trapping code for asp.net web service and jquery combo.
Thanks!
Very interesting topic will bookmark your site to check if you write more about in the future. I’m not getting older…I’m getting bitter
nice tuto in here , good introduction , look at mine in my website righ here http://help.uk.cm.
hear from you soon thanks…
Hi, nice solution.
I tried it and it works fine on my dev machine and on the server ‘locally’. But when I try it from outside the server, the server does not send content-type of application/json while it does locally and on my dev machine.
What the server is doing, when I call the Web site on the server externally, it replaces the error josn text with the server response which is (Bad Request or Internal Server Error), then cannot parse JSON.
Any idea.
Thanks.
This does not work on IIS. IIS does not return application/json as content tyep. Is their anyway to enable this behaviour for IIS
Hi, I have also came to this solution and it works fine when I connect to the server from the server itself but when I connect remotely from a different computer I only get “Bad Request” at the response and not the JSON itself, any ideas maybe ?
Hey Sumit,
Thanks for sharing! 🙂
For anyone interested here’s an improvement to code shown in this post:
http://www.leniel.net/2013/12/getting-aspnet-mvc-action-exception-message-on-ajax-fail-error-callback.html
You share interesting things here. I think that your
blog can go viral easily, but you must give
it initial boost and i know how to do it, just search in google for – mundillo traffic increase
go viral