Dashu
Dashu

Reputation: 347

MVC 3 json request should receive json response on exception

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.

Upvotes: 3

Views: 1630

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

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

Upvotes: 7

Jim Bolla
Jim Bolla

Reputation: 8295

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.

Upvotes: 0

Related Questions