Dav*_*den 12 exception-handling asp.net-web-api2
在关于实施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?
我做了,并且在调试控制器操作中生成的异常时,两个实现都处理了异常.因此IExceptionLogger,文章中引用的所有原因都是优越的.我们应该考虑ExceptionFilterAttribute弃用吗?如果没有,为什么不呢?
再谈这个话题,我终于有了一个更好的理解之间的关系IExceptionLogger,ExceptionFilterAttribute以及IExceptionHandler。
来自问题的不同文档来源:
我们提供了两个新的用户可替换服务,IExceptionLogger 和 IExceptionHandler,用于记录和处理未处理的异常。这些服务非常相似,但有两个主要区别: 我们支持注册多个异常记录器,但只支持注册一个异常处理程序。异常记录器总是被调用,即使我们要中止连接。只有当我们仍然能够选择要发送的响应消息时,才会调用异常处理程序。这两种服务都提供对异常上下文的访问,该上下文包含来自检测到异常的点的相关信息,特别是 HttpRequestMessage、HttpRequestContext、抛出的异常和异常源(详情如下)。
以及问题的实际答案:
异常记录器是查看 Web API 捕获的所有未处理异常的解决方案。异常处理程序是自定义对 Web API 捕获的未处理异常的所有可能响应的解决方案。异常过滤器是处理与特定操作或控制器相关的未处理异常子集的最简单解决方案。
以及说明各种类/接口之间关系的相关代码块(从 反编译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;
}
Run Code Online (Sandbox Code Playgroud)