Sergey Metlov
Sergey Metlov

Reputation: 26291

Return special JsonResult in case of Exception occurs

public JsonResult Menu() { // Exception }

I need application not to redirect user to the 404 page, but return special JSON result like { "result":1 }.
I wonder, is there any another solution, not try-catching.

Upvotes: 3

Views: 1069

Answers (1)

Rune
Rune

Reputation: 8380

You can implement your own FilterAttribute similar to the HandleErrorAttribute.

The HandleErrorAttribute normally does a redirect when an error occurs, but you could implement a similar attribute that returns a JsonResult. Something like the following will do:

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

I would recommend that you download the MVC source code from CodePlex and inspect the current implementation of HandleErrorAttribute. It is a lot more subtle than my crude implementation above and you may want some of its functionality.

Upvotes: 6

Related Questions