Reputation: 347
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
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
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