Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

How can I pass custom error information from an ASP.NET MVC3 JsonResult method to the error (or success or complete, if need be) function of jQuery.ajax()? Ideally I'd like to be able to:

  • Still throw the error on the server (this is used for logging)
  • Retrieve custom information about the error on the client

Here is a basic version of my code:

Controller JsonResult method

public JsonResult DoStuff(string argString)
{
    string errorInfo = "";

    try
    {
        DoOtherStuff(argString);
    }
    catch(Exception e)
    {
        errorInfo = "Failed to call DoOtherStuff()";
        //Edit HTTP Response here to include 'errorInfo' ?
        throw e;
    }

    return Json(true);
}

JavaScript

$.ajax({
    type: "POST",
    url: "../MyController/DoStuff",
    data: {argString: "arg string"},
    dataType: "json",
    traditional: true,
    success: function(data, statusCode, xhr){
        if (data === true)
            //Success handling
        else
            //Error handling here? But error still needs to be thrown on server...
    },
    error: function(xhr, errorType, exception) {
        //Here 'exception' is 'Internal Server Error'
        //Haven't had luck editing the Response on the server to pass something here
    }
});

Things I've tried (that didn't work out):

  • Returning error info from catch block
    • This works, but the exception can't be thrown
  • Editing HTTP response in catch block
    • Then inspected xhr in the jQuery error handler
    • xhr.getResponseHeader(), etc. contained the default ASP.NET error page, but none of my information
    • I think this may be possible, but I just did it wrong?
share|improve this question

4 Answers

up vote 12 down vote accepted

You could write a custom error filter:

public class JsonExceptionFilterAttribute : FilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
        {
            filterContext.HttpContext.Response.StatusCode = 500;
            filterContext.ExceptionHandled = true;
            filterContext.Result = new JsonResult
            {
                Data = new
                {
                    // obviously here you could include whatever information you want about the exception
                    // for example if you have some custom exceptions you could test
                    // the type of the actual exception and extract additional data
                    // For the sake of simplicity let's suppose that we want to
                    // send only the exception message to the client
                    errorMessage = filterContext.Exception.Message
                },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }
    }
}

and then register it either as a global filter or only apply to particular controllers/actions that you intend to invoke with AJAX.

And on the client:

$.ajax({
    type: "POST",
    url: "@Url.Action("DoStuff", "My")",
    data: { argString: "arg string" },
    dataType: "json",
    traditional: true,
    success: function(data) {
        //Success handling
    },
    error: function(xhr) {
        try {
            // a try/catch is recommended as the error handler
            // could occur in many events and there might not be
            // a JSON response from the server
            var json = $.parseJSON(xhr.responseText);
            alert(json.errorMessage);
        } catch(e) { 
            alert('something bad happened');
        }
    }
});

Obviously you could be quickly bored to write repetitive error handling code for each AJAX request so it would be better to write it once for all AJAX requests on your page:

$(document).ajaxError(function (evt, xhr) {
    try {
        var json = $.parseJSON(xhr.responseText);
        alert(json.errorMessage);
    } catch (e) { 
        alert('something bad happened');
    }
});

and then:

$.ajax({
    type: "POST",
    url: "@Url.Action("DoStuff", "My")",
    data: { argString: "arg string" },
    dataType: "json",
    traditional: true,
    success: function(data) {
        //Success handling
    }
});

Another possibility is to adapt a global exception handler I presented so that inside the ErrorController you check if it was an AJAX request and simply return the exception details as JSON.

share|improve this answer
+1, pretty nice answer! – Mark Schultheiss Feb 15 '12 at 18:14
Great answer! Quick question: how can I override the default error handling? Say I have the $(document).ajaxError handler, but I also want to handle the error myself on certain ajax calls and prevent the default error handling behaviour. Is this possible? – Lindsay Oct 15 '12 at 14:30

you can return JsonResult with error and track the status at javascript side to show error message :

 JsonResult jsonOutput = null;
        try
        {
           // do Stuff
        }
        catch
        {
            jsonOutput = Json(
                 new
                 {
                     reply = new
                     {
                         status = "Failed",
                         message = "Custom message "
                     }
                 });
        }
        return jsonOutput ;
share|improve this answer

This is how I would handle my errors:

    $.ajax({
        type: "POST",
        url: "../MyController/DoStuff",
        data: {argString: "arg string"},
        dataType: "json",
        traditional: true,
        success: 
        function(data, statusCode, xhr){
        //Success handling
        },
         error: AjaxFailed
        }
    });

        function AjaxFailed(result) {
            alert(result.status + ' ' + result.statusText);
        }
share|improve this answer

My MVC project wasn't returning any error message (custom or otherwise). I found that this worked well for me:

$.ajax({
        url: '/SomePath/Create',
        data: JSON.stringify(salesmain),
        type: 'POST',
        contentType: 'application/json;',
        dataType: 'json',
        success: function (result) {

            alert("start JSON");
            if (result.Success == "1") {
                window.location.href = "/SomePath/index";
            }
            else {
                alert(result.ex);
            }

            alert("end JSON");
        },
        error: function (xhr) {

            alert(xhr.responseText);

        }
        //error: AjaxFailed
    });

Showing the xhr.responseText resulted in a very detailed HTML formatted alert message.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.