爲什麼自定義的ExceptionHandler
永遠不會被調用,而是返回一個標準響應(不是我想要的)?WebApi v2 ExceptionHandler not called
在控制器或在儲存庫中註冊這樣
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");
。
UPDATE
我沒有其他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(網站)上託管時發生,但內置錯誤處理程序不同。
任何想法如何解決這個問題?
你碰巧有一個異常過濾器呢?也可以大家分享您的控制器或庫代碼的樣子......我們想確保你沒有地方捕獲它並將其轉換爲HttpResponseException什麼在這種情況下,異常處理程序不會被調用。 –
@KiranChalla:上面有趣的更新,謝謝! –