【问题标题】:When does a .net core exception filter get called after an exception is thrown?抛出异常后何时调用 .net 核心异常过滤器?
【发布时间】:2019-01-28 19:51:50
【问题描述】:

在我的 api 中,我有一个包含操作的标准控制器,该操作调用服务,然后调用客户端以联系其他第三方 api。

我希望实现类似于以下内容的异常过滤器:

public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
{
    private readonly IHostingEnvironment _hostingEnvironment;
    private readonly IModelMetadataProvider _modelMetadataProvider;

    public CustomExceptionFilterAttribute(
        IHostingEnvironment hostingEnvironment,
        IModelMetadataProvider modelMetadataProvider)
    {
        _hostingEnvironment = hostingEnvironment;
        _modelMetadataProvider = modelMetadataProvider;
    }

    public override void OnException(ExceptionContext context)
    {
        if (!_hostingEnvironment.IsDevelopment())
        {
            // do nothing
            return;
        }
        var result = new ViewResult {ViewName = "CustomError"};
        result.ViewData = new ViewDataDictionary(_modelMetadataProvider,context.ModelState);
        result.ViewData.Add("Exception", context.Exception);
        // TODO: Pass additional detailed data via ViewData
        context.Result = result;
    }
}

如果我的客户端类例如抛出异常,过滤器是否会立即被调用,即使我调用客户端类的服务类已经准备好捕获此类异常?

【问题讨论】:

  • 请提供一些代码。
  • 我将添加与问题中链接的完全相同的代码。我认为这就足够了。
  • 我不知道你在问什么。
  • 根据问题的最后两行,我认为这不会更清楚。
  • 请提供minimal reproducible exampleclient是谁?

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


【解决方案1】:

没有。根据documentation you refer to,异常过滤器只会被未处理的异常触发;如果客户端异常由服务处理并且没有重新抛出,则异常过滤器不会触发。

异常过滤器:

  • 没有前后事件。
  • 实现 OnException 或 OnExceptionAsync。
  • 处理控制器创建、模型绑定、动作过滤器或动作方法中发生的未处理异常。
  • 不要捕获资源过滤器、结果过滤器或 MVC 结果执行中发生的异常。

【讨论】:

    猜你喜欢
    • 2017-06-29
    • 2019-05-29
    • 2021-11-05
    • 1970-01-01
    • 2013-05-24
    • 1970-01-01
    • 2013-09-07
    • 2017-04-20
    • 1970-01-01
    相关资源
    最近更新 更多