views:

1239

answers:

2

I'm using a filter to log exceptions thrown by actions which looks like this:

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

Now I'd like to handle all my JSON actions to return JSON result with exception information. This allows the Ajax calls to determine if there was any error on the server instead of receiving the error page source, which is useless for Ajax. I've implemented 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 nice, but obviously the catch() statement prevents all filters from handling the exception, because there's no exception thrown actually. Is there any way how to leave exception available for filters (filterContext.Exception)?

+1  A: 

You could store the exception in the RequestContext and intercept it in your filter.

Kris
A: 

The solution:

action

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

filter

    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);
    }
Buthrakaur
ari