在我的C#Web API中,我试图添加一个全局异常处理程序。我一直在使用一个自定义的全球ExceptionFilterAttribute
来处理异常,并返回一个HttpResponseMessage
:Web API OWIN启动异常处理
public override void OnException(HttpActionExecutedContext context)
{
...
const string message = "An unhandled exception was raised by the Web API.";
var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new StringContent(message),
ReasonPhrase = message
};
context.Response = httpResponseMessage;
}
这一直很好处理在控制器级别抛出异常。
但是,在开发过程中,由于数据库连接问题,我们的OWIN启动文件出现错误,但是,返回了标准IIS异常,而不是通过全局异常处理程序,并且完整的HTML返回我们的API消费者。
我已经尝试了几种不同的方法,以赶上我OWIN启动抛出的异常:
定制ApiControllerActionInvoker
:
public class CustomActionInvoker : ApiControllerActionInvoker
{
public override Task<HttpResponseMessage> InvokeActionAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
{
var result = base.InvokeActionAsync(actionContext, cancellationToken);
if (result.Exception != null && result.Exception.GetBaseException() != null)
{
...
}
return result;
}
}
定制ExceptionHandler
:
public class CustomExceptionHandler : ExceptionHandler
{
public override void Handle(ExceptionHandlerContext context)
{
...
base.Handle(context);
}
public override bool ShouldHandle(ExceptionHandlerContext context)
{
return true;
}
}
定制OwinMiddleware
组件:
public class CustomExceptionMiddleware : OwinMiddleware
{
public CustomExceptionMiddleware(OwinMiddleware next) : base(next)
{
}
public override async Task Invoke(IOwinContext context)
{
try
{
await Next.Invoke(context);
}
catch (Exception ex)
{
...
}
}
}
最后只用Application_Error
:
protected void Application_Error(object sender, EventArgs e)
{
...
}
但似乎没有捕获异常。
有谁知道一种方法来捕捉异常并返回HttpResponseMessage
?或者,如果我已经尝试的任何方法应该工作?
任何帮助非常感谢。
如果这些都没有工作,你可以订阅的'AppDomain'.This的'UnhandledException'事件必须触发一次有一种情况例外,有没有适当的处理程序来处理异常。 –
感谢您的评论。我刚刚尝试通过'Application_Start'方法添加订阅'UnhandledException',但它似乎没有捕获。 'UnhandledException'确实可以通过Web API工作吗? –
以及文档说,这是在任何未处理的异常情况下必须触发的事件。 –