你是对的,有几类异常没有被 Application_Error 或 ExceptionFilter 捕获。Web API 请求管道与 ASP.NET MVC 管道分开处理(至少通过 MVC 4),因此 MVC Application_Error 不会启动。此外,如果您的应用程序抛出HttpResponseException
类型异常,它们将不会被ExceptionFilter
设计捕获(参见ExceptionFilter
段落)。要访问您的代码引发的所有异常,您需要按照DelegatingHandler
此代码的行创建一个:
public class ResponseExceptionTrapper : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
return base
.SendAsync(request, cancellationToken)
.ContinueWith(response =>
{
var result = response.Result;
if (!result.IsSuccessStatusCode)
{
var exceptionResult = string.Format(
"Response exception: Path({0}) Status({1}) ",
request.RequestUri,
result.StatusCode);
if (result.Content != null)
{
var exceptionReadTask =
result.Content.ReadAsStringAsync();
exceptionReadTask.Wait();
exceptionResult += "Message:\n\r" +
exceptionReadTask.Result;
}
// Do something appropriate with exceptionResult
}
return result;
}, cancellationToken);
}
}
您可以在全局配置逻辑中使用此行连接处理程序:
GlobalConfiguration.Configuration.MessageHandlers.Add(
new ResponseExceptionTrapper());