为什么自定义的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");
在控制器或存储库中。
更新
我没有另一个ExceptionFilter
。
我发现了这种行为的触发器:
给定的URL
GET http://localhost:XXXXX/template/lock/someId
通过发送这个头信息,我的 ExceptionHandler
就会工作了。
Host: localhost:XXXXX
发送这个头信息时,它无效,而内置的处理程序会返回错误。Host: localhost:XXXXX
Origin: http://localhost:YYYY
这可能是由于CORS请求问题(我全局使用WebAPI CORS包和通配符)或我的ELMAH日志记录器。即使在Azure上托管(网站),也会发生这种情况,尽管内置的错误处理程序不同。有任何解决方法吗?