Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)?

like image 871
Buthrakaur Avatar asked Apr 10 '09 08:04

Buthrakaur


1 Answers

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

like image 98
Kris Avatar answered Oct 13 '22 01:10

Kris