3

I'm looking for a good/smart/clean way to globally handle errors so that if a request is Json and an exception occurs, the result should be json and not html.

Looking for either existing solutions or some info of how to build my own.

2 Answers 2

7

One common way to do this is to write a custom exception filter:

public class MyErrorHandlerAttribute : FilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        filterContext.ExceptionHandled = true;
        filterContext.Result = new JsonResult
        {
            Data = new { success = false, error = filterContext.Exception.ToString() },
            JsonRequestBehavior = JsonRequestBehavior.AllowGet
        };
    }
}

which could be registered as a global filter in Global.asax. And then simply query some action:

$.getJSON('/someController/someAction', function (result) {
    if (!result.success) {
        alert(result.error);
    } else {
        // handle the success
    }
});
Sign up to request clarification or add additional context in comments.

5 Comments

Wouldn't this run for every exception?
@Dashu, yes for every exception. You could also test whether the request was an AJAX request and whether the request content type was application/json and only in this case handle the exception.
It's interesting, but how can you get your result on a Ajax.Error event? The idea you posted was using $.getJson, so how would you do it using the full $.ajax, including the error event?
@AdrianoRR, the error event is trigerred only if a non-200 is sent from the server.
@Darin, i know that. That's why im asking how can i return the JsonResult data to the ajax Error event. An other thing, if it reached the OnException event, wouldn't it throw a non-200 error?
0

This is probably doable with a custom attribute... maybe even a subclass of HandleErrorAttribute. The trick will be how to know if a controller action was going to return JSON or not. This could be as simple as suffixing those method names such as GetCustomerDetailsJson.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.