如何捕获ASP.NET Web Api中发生的所有未处理的异常,以便我可以记录它们?
到目前为止,我尝试过:
ExceptionHandlingAttributeApplication_Error方法Global.asax.csAppDomain.CurrentDomain.UnhandledExceptionTaskScheduler.UnobservedTaskException在ExceptionHandlingAttribute成功处理时引发的控制器操作方法和操作筛选范围内,但其他异常没有被处理,例如例外:
IQueryableaction方法返回的异常无法执行时抛出的异常HttpConfiguration.MessageHandlers)基本上,如果异常将导致500内部服务器错误返回到客户端,我希望它被记录.实现Application_Error在Web窗体和MVC中完成了这项工作 - 我可以在Web Api中使用什么?
我创建了一个自定义Web API全局异常处理程序,如下所示:
public class MyGlobalExceptionHandler : ExceptionHandler
{
public override void Handle(ExceptionHandlerContext context)
{
// here I handle them all, no matter sync or not
}
public override Task HandleAsync(ExceptionHandlerContext context,
CancellationToken cancellationToken)
{
// not needed, but I left it to debug and find out why it never reaches Handle() method
return base.HandleAsync(context, cancellationToken);
}
public override bool ShouldHandle(ExceptionHandlerContext context)
{
// not needed, but I left it to debug and find out why it never reaches Handle() method …Run Code Online (Sandbox Code Playgroud) 当控制器中抛出某些异常时,我想捕获这些异常并执行一些额外的逻辑。
我能够通过添加到全局过滤器列表中的自定义 IExceptionFilter 来实现此目的。
但是,我更喜欢在自定义 Owin 中间件中处理这些异常。我的中间件如下所示:
try
{
await Next.Invoke(context);
}
catch (AdalSilentTokenAcquisitionException e)
{
//custom logic
}
Run Code Online (Sandbox Code Playgroud)
这段代码不起作用,看起来异常已经在 MVC 中捕获并处理了。有没有办法跳过MVC的异常处理并让中间件捕获异常?