【发布时间】:2014-04-05 20:47:22
【问题描述】:
为什么从来没有调用自定义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。
我找到了这种行为的触发因素:
给定网址
GET http://localhost:XXXXX/template/lock/someId
发送此标头,我的 ExceptionHandler 有效
Host: localhost:XXXXX
发送此标头,它不起作用,内置处理程序会返回错误
Host: localhost:XXXXX
Origin: http://localhost:YYYY
这可能是 CORS 请求的问题(我在全局范围内使用带有通配符的 WebAPI CORS 包)或最终是我的 ELMAH 记录器。托管在 Azure(网站)上时也会发生这种情况,尽管内置的错误处理程序不同。
知道如何解决这个问题吗?
【问题讨论】:
-
你也有异常过滤器吗?您还可以分享您的控制器或存储库代码的外观...我们希望确保您没有在某处捕获它并将其转换为 HttpResponseException 或在这种情况下不会调用异常处理程序的东西。
-
@KiranChalla:上面有有趣的更新,谢谢!
标签: c# asp.net-web-api