首页 > 解决方案 > 为什么异常处理程序中间件在实际处理时会记录“未处理的异常”?

问题描述

我的应用程序中有一个非常简单的异常处理程序中间件:

app.UseExceptionHandler(a =>a.Run(async context =>{
  var exceptionHandlerPathFeature = context.Features.Get < IExceptionHandlerPathFeature > ();
  var exception = exceptionHandlerPathFeature.Error;

  var result = JsonConvert.SerializeObject(new {
    error = exception.GetType().ToString(),
    message = exception.Message
  });
  context.Response.ContentType = "application/json";

  if (exception is NotFoundException) {
    context.Response.StatusCode = 404;
  }
  else {
    context.Response.StatusCode = 500;
  }

  await context.Response.WriteAsync(result);
}));

当我 throwNotFoundException时,中间件捕获异常并按预期向客户端返回 404 消息。但是,由于某种原因,它会记录整个异常堆栈跟踪并告诉我该异常未处理。

Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[1]
      An unhandled exception has occurred while executing the request.

如果异常实际上是由中间件处理的,为什么它会记录堆栈跟踪并说异常没有被处理?NotFound()除了直接在控制器级别返回 a 之外,我还能做些什么来保持我的日志干净?

标签: c#exception.net-core

解决方案


术语“未处理的异常”来自控制器的角度(文档)。

这些过滤器处理在执行控制器操作或另一个过滤器期间发生的任何未处理的异常。

要回答日志显示未处理异常的原因,您可以查看ExceptionHandlerMiddleware的源代码,

private async Task HandleException(HttpContext context, ExceptionDispatchInfo edi)
{
    _logger.UnhandledException(edi.SourceException);
    // Exclude the rest of implementation
}

其中UnhandledException记录“未处理的异常”。

// ExceptionHandlerMiddleware & DeveloperExceptionPageMiddleware
private static readonly Action<ILogger, Exception> _unhandledException =
    LoggerMessage.Define(LogLevel.Error, new EventId(1, "UnhandledException"), "An unhandled exception has occurred while executing the request.");

推荐阅读