ExceptionFilterAttribute

ExceptionFilterAttribute

继从官方文档上实现的IExceptionLogger(http://www.asp.net/web-api/overview/testing-and-debugging/web-api-global-error-handling),它链接到讨论(现已过时?)上实现一个ExceptionFilterAttribute(http://www.asp.net/web-api/overview/testing-and-debugging/exception-handling)的文章,没有任何理由,如果你ExceptionFilterAttribute注册服务注册一个全局IExceptionLogger

我做到了,在调试 Controller 操作中生成的异常时,两个实现都处理了异常。因此,由于文章中引用的所有原因,IExceptionLogger 是优越的。我们应该考虑弃用 ExceptionFilterAttribute 吗?如果没有,为什么不呢?

最佳答案

重温这个话题,我终于对 IExceptionLoggerExceptionFilterAttributeIExceptionHandler 之间的关系有了更好的理解。

来自问题的不同 source of documentation :



以及问题的实际答案:



以及说明各种类/接口(interface)之间关系的相关代码块(从 ExceptionFilterResult 反编译):

public async Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
  ExceptionDispatchInfo exceptionInfo;
  try
  {
    return await this._innerResult.ExecuteAsync(cancellationToken);
  }
  catch (Exception ex)
  {
    exceptionInfo = ExceptionDispatchInfo.Capture(ex);
  }
  Exception exception = exceptionInfo.SourceException;
  bool isCancellationException = exception is OperationCanceledException;
  ExceptionContext exceptionContext = new ExceptionContext(exception, ExceptionCatchBlocks.IExceptionFilter, this._context);
  if (!isCancellationException)
    await this._exceptionLogger.LogAsync(exceptionContext, cancellationToken);
  HttpActionExecutedContext executedContext = new HttpActionExecutedContext(this._context, exception);
  for (int i = this._filters.Length - 1; i >= 0; --i)
  {
    IExceptionFilter exceptionFilter = this._filters[i];
    await exceptionFilter.ExecuteExceptionFilterAsync(executedContext, cancellationToken);
  }
  if (executedContext.Response == null && !isCancellationException)
    executedContext.Response = await this._exceptionHandler.HandleAsync(exceptionContext, cancellationToken);
  if (executedContext.Response != null)
    return executedContext.Response;
  if (exception == executedContext.Exception)
    exceptionInfo.Throw();
  throw executedContext.Exception;
}

关于exception-handling - IExceptionLogger 是否不赞成在 Web API 2 中使用 ExceptionFilterAttribute?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25476475/

10-13 09:32