Return special JsonResult in case of exception

public JsonResult Menu() { // Exception }

I need an application in order not to redirect the user to the 404 page, but return a special JSON result, for example {"result": 1}.
I wonder if there is any other solution, not an attempt to capture.

+3
source share
1 answer

You can implement your own FilterAttribute, similar to HandleErrorAttribute.

HandleErrorAttribute usually redirects when an error occurs, but you can implement a similar attribute that JsonResult returns. Something like the following:

public class CustomHandleErrorAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        if (filterContext == null)
        {
            throw new ArgumentNullException("filterContext");
        }

        filterContext.Result = new JsonResult
        {
            Data = new { result = 1 },
            JsonRequestBehavior = JsonRequestBehavior.AllowGet
        };
        filterContext.ExceptionHandled = true;
    }
}

And then

[CustomHandleError]
public JsonResult Menu()
{
    throw new Exception();
}

MVC CodePlex HandleErrorAttribute. , , .

+6

Source: https://habr.com/ru/post/1790335/


All Articles