Handling Exceptions using jQuery and ASP.NET MVC

Posted in AJAX, ASPNETMVC, jquery by Sumit Thomas on December 22, 2009

[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()
                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() {
                type: "GET",
                url: "AJAX/DivideByZero",
                dataType: "json",
                success: function(data) {
                    if (data) {
                }, error: function(xhr, status, error) {

        function DisplayError(xhr) {
            var msg = JSON.parse(xhr.responseText);

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!

Tagged with: , ,

20 Responses

Subscribe to comments with RSS.

  1. Erik said, on December 22, 2009 at 6:26 pm

    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.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.



    • 2leggedspider said, on December 22, 2009 at 6:52 pm

      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 🙂


      • Erik said, on December 22, 2009 at 7:39 pm

        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.


  2. jbland said, on December 22, 2009 at 8:16 pm

    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.

  3. Erik said, on December 22, 2009 at 8:44 pm

    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.



    • 2leggedspider said, on December 23, 2009 at 5:41 pm

      Hey Eric,

      Nice stuff! Its lot better than what I’ve done.

      Thanks for sharing 🙂


    • brogits said, on October 7, 2010 at 10:55 am

      hi Erik,

      Can you repost the link. It seems to be dead

  4. ASP.NET MVC Archived Buzz, Page 1 said, on December 22, 2009 at 9:20 pm

    […] to Vote[FriendFeed] Handling Exceptions using jQuery and ASP.NET MVC 2LeggedSpider (12/22/2009)Tuesday, December 22, 2009 from […]

  5. Neal said, on December 22, 2009 at 11:42 pm

    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.

    • 2leggedspider said, on December 23, 2009 at 5:46 pm


      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 🙂


  6. rana said, on December 23, 2009 at 4:15 pm

    nice tutorial. Thanks for sharing.

  7. Jenny F said, on January 27, 2010 at 3:02 am

    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.


  8. Loan said, on February 10, 2010 at 7:55 am

    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

  9. bigman said, on March 6, 2010 at 8:45 pm

    nice tuto in here , good introduction , look at mine in my website righ here http://help.uk.cm.

    hear from you soon thanks…

  10. George said, on January 8, 2011 at 12:49 pm

    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.


  11. William Smith said, on August 20, 2012 at 12:27 pm

    This does not work on IIS. IIS does not return application/json as content tyep. Is their anyway to enable this behaviour for IIS

  12. Eran said, on January 18, 2013 at 7:52 am

    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 ?

  13. Leniel Macaferi said, on December 26, 2013 at 9:37 am

    Hey Sumit,

    Thanks for sharing! 🙂

    For anyone interested here’s an improvement to code shown in this post:


  14. Eugenia said, on October 8, 2014 at 1:53 pm

    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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: