3

I've seen multiple ways to return a custom exception from the controller back to an ajax call. I'm wondering what the best practices or preferred methods are so that I can start to standardize all of the ajax calls in my project.

I just want to highlight two ways I've seen of handling ajax exceptions and come to a conclusion about which is "better".

I apologize if there is a post/response that already answers this question, but I searched quite a bit and could not find a definitive answer.

Environment info: using MVC 4, .Net 4.5, jQuery 1.10.2

Method 1:

One example I've seen of handling custom errors is from a response to another post on this site that describes creating a custom error filter. So in this case I would have:

JsonExceptionFilterFilter

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
            };
        }
    }
}

My controller action would then look like:

[HttpPost]
[JsonExceptionFilter]
public ActionResult MyAction() {

    // do things

    if(some conditional here is false) {
        // the custom exception thrown here will be processed by the JsonExceptionFilter
        // so that the ajax call actually recognizes that an exception occurred.
        throw new CustomException(); 
    }

    return View()
}

You'll then see the HTTP 500 error when looking at Firebug or Chrome devtools. By using this custom error filter, the $.ajax.fail() would actually be hit.

$.ajax({
    type: 'POST',
    url: '/MyAction/MyController',
    data:{ ... }
}).done(function(response) {
    // process a successful response
}).fail(function(xhr) {
    // My custom error thrown in the controller gets caught here
});

Method 2:

The second method I see a lot is to just return a Json object that contains a boolean value for whether or not the request was successful.

[HttpPost]
public ActionResult MyAction() {

    // do stuff

    if(some condition here is false) {
        return Json(new { errorOccurred=true, errorMessage="something failed" });
    }

    // do stuff

    return View()
}

The one annoyance I see with this method is that you're always required to check if the request was successful or not:

$.ajax({
    type: 'POST',
    url: '/MyAction/MyController',
    data:{ ... }
}).done(function(response) {
    if(response.errorOccurred) {
        // display the error message to the user
    }
    else {
        // continue processing the successful response
    }
});

So out of those two methods, which one is typically the preferred or "better" way of doing things? Or is there a third option that is the new standard for handling ajax exceptions? Both ways get the job done, but I do think that implementing the custom filter is cleaner and allows for better debugging.

Thanks in advance for any advice.

Community
  • 1
  • 1

0 Answers0