ASP.Net MVC - how to handle an exception in a JSON action (return JSON error information), but also publish an exception for filters?

I use a filter to register exceptions thrown by actions that look like this:

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if (filterContext.Exception != null)
        {
           //logger.Error(xxx);
        }
        base.OnActionExecuted(filterContext);
    }

Now I would like to process all my JSON actions to return a JSON result with exception information. This allows Ajax calls to determine if there was any error on the server instead of getting the source of the error page, which is useless for Ajax. I applied this method for JSON actions in my AppControllerBase:

    public ActionResult JsonExceptionHandler(Func<object> action)
    {
        try
        {
            var res = action();
            return res == null ? JsonSuccess() : JsonSuccess(res);
        }
        catch(Exception exc)
        {
            return JsonFailure(new {errorMessage = exc.Message});
        }
    }

This works well, but obviously the catch () statement prevents all filters from handling the exception, because the exception is not really possible. Is there a way to leave an exception available for filters (filterContext.Exception)?

+5
2

:

    public ActionResult JsonExceptionHandler(Func<object> action)
    {
            try
            {
                    var res = action();
                    return res == null ? JsonSuccess() : JsonSuccess(res);
            }
            catch(Exception exc)
            {
                    controller.ControllerContext.HttpContext.AddError(exc);
                    return JsonFailure(new {errorMessage = exc.Message});
            }
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
            var exception = filterContext.Exception ?? filterContext.HttpContext.Error;
            if (exception != null)
            {
               //logger.Error(xxx);
            }

            if (filterContext.Result != null && 
                filterContext.HttpContext.Error != null)
            {
               filterContext.HttpContext.ClearError();
            }

            base.OnActionExecuted(filterContext);
    }
-1

RequestContext .

+1

All Articles