简体   繁体   中英

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

您可以将异常存储在 RequestContext 中并在您的过滤器中拦截它。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM