为什么从未调用自定义 ExceptionHandler
而是返回标准响应(不是我想要的响应)?
这样注册
config.Services.Add(typeof(IExceptionLogger), new ElmahExceptionLogger());
config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler());
然后这样实现
public class GlobalExceptionHandler : ExceptionHandler
{
public override void Handle(ExceptionHandlerContext context)
{
context.Result = new ExceptionResponse
{
statusCode = context.Exception is SecurityException ? HttpStatusCode.Unauthorized : HttpStatusCode.InternalServerError,
message = "An internal exception occurred. We'll take care of it.",
request = context.Request
};
}
}
public class ExceptionResponse : IHttpActionResult
{
public HttpStatusCode statusCode { get; set; }
public string message { get; set; }
public HttpRequestMessage request { get; set; }
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var response = new HttpResponseMessage(statusCode);
response.RequestMessage = request;
response.Content = new StringContent(message);
return Task.FromResult(response);
}
}
然后像这样抛出(测试)
throw new NullReferenceException("testerror");
在 Controller 或存储库中。
更新
我没有另一个 ExceptionFilter
。
我发现了这种行为的诱因:
给定的网址
GET http://localhost:XXXXX/template/lock/someId
发送这个 header ,我的ExceptionHandler
工作
Host: localhost:XXXXX
发送这个 header ,它不起作用,内置处理程序反而返回错误
Host: localhost:XXXXX
Origin: http://localhost:YYYY
这可能是 CORS 请求(我在全局范围内使用带有通配符的 WebAPI CORS 包)或最终是我的 ELMAH 记录器的问题。当托管在 Azure(网站)上时也会发生这种情况,尽管内置的错误处理程序不同。
知道如何解决这个问题吗?
最佳答案
原来默认只处理最外层的异常,不处理存储库类中的异常。所以下面也必须被覆盖:
public virtual bool ShouldHandle(ExceptionHandlerContext context)
{
return context.ExceptionContext.IsOutermostCatchBlock;
}
更新 1
WebAPI v2 不再使用 IsOutermostCatchBlock
。无论如何,我的实现没有任何变化,因为 ShouldHandle
中的新代码仍然阻止我的错误处理程序。所以我正在使用它并且我的错误处理程序被调用一次。我通过这种方式捕获 Controller 和存储库中的错误。
public virtual bool ShouldHandle(ExceptionHandlerContext context)
{
return true;
}
更新 2
由于这个问题受到了如此多的关注,请注意当前的解决方案是linked。 @JustAMartin 在下面的评论中发表。
关于c# - 未调用 WebApi v2 ExceptionHandler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22169889/