【问题标题】:When can IExceptionHandlerPathFeature be null with ExceptionHandlerMiddleware in Asp.Net Core什么时候 IExceptionHandlerPathFeature 可以在 Asp.Net Core 中使用 ExceptionHandlerMiddleware 为空
【发布时间】:2019-03-14 15:43:32
【问题描述】:

Microsoft 为ExceptionHandlerMiddleware here 提供了此示例。这是一段摘录:

app.UseExceptionHandler(errorApp =>
{
    errorApp.Run(async context =>
    {
        ...

        var exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>();

        if (exceptionHandlerPathFeature?.Error is FileNotFoundException)
        {
            await context.Response.WriteAsync("File error thrown!");
        }

        ...
    });
});

我不太明白他们为什么要使用?. 运算符来获取异常?可以在没有IExceptionHandlerPathFeature 的情况下触发此委托吗?没有保证访问异常的异常处理程序似乎不合逻辑。

Here 是代码,其中似乎不可能有 null。

【问题讨论】:

  • 如果IExceptionHandlerPathFeature 实现无法找到一些阅读,那么它可能是null
  • 理论上是可能的,但它只是practice中的POCO
  • 如果在context.Features集合中没有找到exceptionHandlerPathFeature,则可能为null的不是错误
  • 是的,据我所见,它可以是null,但我目前并不完全了解这些情况。
  • 在正常情况下,它永远不会为空。但是,您可以简单地实现IWebHost 非常,它会的。默认实现将具有此功能,但这并不意味着所有实现都会。除此之外,始终围绕空值进行编码只是一种好习惯。也许它永远不会为空,但有一个 潜在 为空,所以这种情况被覆盖了。这对于异常处理程序来说可能尤其重要,因为您可能会从抛出异常的处理程序本身陷入无限循环。

标签: c# exception asp.net-core .net-core


【解决方案1】:

在我的特殊情况下,我有一个带有以下操作之一的自定义错误控制器:

[Route("Error")]
public IActionResult Error(ErrorViewModel model)
{
    var exceptionDetails = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
    model.Code = 500;

    _logger.Error($"The path {exceptionDetails?.Path} threw an exception " +
         $"{exceptionDetails?.Error}");

    return View(nameof(Error), model);
}

IExceptionHandlerPathFeature 在用户手动在浏览器中手动输入我的错误页面路由时为空。所以我只好放空条件运算符来限制空引用异常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-24
    • 1970-01-01
    • 2013-03-24
    • 1970-01-01
    • 1970-01-01
    • 2012-07-09
    • 2010-12-28
    相关资源
    最近更新 更多