c# - 为什么异常处理程序中间件在实际处理时会记录“未处理的异常”?
问题描述
我的应用程序中有一个非常简单的异常处理程序中间件:
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 之外,我还能做些什么来保持我的日志干净?
解决方案
术语“未处理的异常”来自控制器的角度(文档)。
这些过滤器处理在执行控制器操作或另一个过滤器期间发生的任何未处理的异常。
要回答日志显示未处理异常的原因,您可以查看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.");
推荐阅读
- kotlin - 如何在“kotlin”中从一个活动过渡到另一个活动,例如从左到右和从右到左?
- python - URL 模板标签在一个实例中有效,但在另一个实例中找不到带有 '{'pk': ''}' 的 kwargs 的路径
- wcf - Biztalk WCF 服务发布向导
- cardano - 用户是否因在 Ouroboros 算法中竞标错误的分叉而受到惩罚?
- javascript - Console.log 到 Document.write
- asp.net-core - 如何使用重写的文件名提供文件?
- php - 如何更新 Amazon CloudFront 分配
- python - 如何获取我刚刚打印的值的单元格的位置?
- javascript - 在Javascript中过滤foreach索引值
- algorithm - 纯 Knuth/Fisher-Yates 在 haskell 中洗牌