MVC 3 json request should receive json response to exception

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

We are looking for either existing solutions or some information on how to create your own.

+3
source share
2 answers

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 can be registered as a global filter in Global.asax. And then just request some action:

$.getJSON('/someController/someAction', function (result) {
    if (!result.success) {
        alert(result.error);
    } else {
        // handle the success
    }
});
+7
source

, , ... , HandleErrorAttribute. , , JSON . , , GetCustomerDetailsJson.

0

All Articles