问题描述
如何来一个自定义的的ExceptionHandler
不会被调用,而是一个标准的响应(不是我想要的)返回?
How comes that a custom ExceptionHandler
is never called and instead a standard response (not the one I want) is returned?
注册这样
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");
在控制器或在资源库中。
in a controller or in a repository.
更新
我没有其他 ExceptionFilter
。
我找到了这种行为触发:
I found a trigger for this behavior:
由于网址
GET http://localhost:XXXXX/template/lock/someId
发送这个头,我的的ExceptionHandler
和
Host: localhost:XXXXX
发送这个头,它不工作,并且内置的处理器将返回错误,而不是
sending this header, it doesn't work and the built-in handler returns the error instead
Host: localhost:XXXXX
Origin: http://localhost:YYYY
这可能与CORS请求(我在全球范围使用的WebAPI CORS包带通配符)或最终我ELMAH记录器的问题。在Azure(网站)主办的时候,虽然内置的错误处理程序不同,它也会发生。
This might be an issue with CORS requests (I use the WebAPI CORS package globally with wildcards) or eventually my ELMAH logger. It also happens when hosted on Azure (Websites), though the built-in error handler is different.
不知道如何解决这个问题?
Any idea how to fix this?
推荐答案
原来默认只处理最外层的异常,在库类不例外。所以下面已被覆盖,以及:
Turns out the default only handles outermost exceptions, not exceptions in repository classes. So below has to be overridden as well:
public virtual bool ShouldHandle(ExceptionHandlerContext context)
{
return context.ExceptionContext.IsOutermostCatchBlock;
}
更新:
的WebAPI V2不使用 IsOutermostCatchBlock
了。反正没有什么改变我的实现,因为在 ShouldHandle
新的code仍prevents我的错误处理程序。所以我用这个和我的错误处理程序被调用一次。我捕捉控制器错误和库本办法。
WebAPI v2 does not use IsOutermostCatchBlock
anymore. Anyway nothing changes in my implementation, since the new code in ShouldHandle
still prevents my Error Handler. So I'm using this and my Error Handler gets called once. I catch errors in Controllers and Repositories this way.
public virtual bool ShouldHandle(ExceptionHandlerContext context)
{
return true;
}
这篇关于V2的WebAPI没有的ExceptionHandler叫的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!