【问题标题】:ExceptionFilterAttribute.OnException not called, when exception thrown from a service当服务抛出异常时,未调用 ExceptionFilterAttribute.OnException
【发布时间】:2018-09-29 21:46:38
【问题描述】:

无法理解 ExceptionFilterAttribute 何时调用 OnException 方法。

假设我有 2 个已注册的过滤器:

filters.Add<ExceptionFilter>();
filters.Add<ActionExecutionFilter>();

ExceptionFilter 覆盖 OnException 并且 ActionExecutionFilter 具有 OnActionExecution 并且出于测试目的它具有 OnResultExecuted。

我发现 - 如果我直接将异常抛出到动作中,它会调用 OnException 方法, 但是如果我在我的任何依赖注入服务中抛出异常(参见示例),那么它不会调用 OnException 方法。当在任何这些情况下发生异常时(第二个示例),我知道 ActionFilter 将调用 OnResultExecuted 方法,我可以在其中看到异常,该异常直接进入中间件异常处理程序。

我想知道的是,如果 Result 中有异常,为什么 ExceptionFilter 不调用任何方法。

例子:

public ActionResult SomeActionMethod()
{
    throw new Exception("this one calls OnException");
    //Logic
}

public ActionResult SomeActionMethod()
{
    var result = this._injectedService.ThrowExceptionMethod(); // --> This one doesn't call OnException if it appears
    //Logic
}

【问题讨论】:

  • 这很奇怪。介意粘贴异常过滤器的内容吗?另外,ThrowExceptionMethod 是异步方法吗(返回 TaskTask&lt;T&gt;)?如果是的话,你会等吗?如果不是,则不会捕获异步方法的异常,除非 a) awaited 或 b) task.Result(阻塞,错误,抛出 AggregateException 而不是特定的)或 c) task.GetAwaiter().GetResult() 被调用
  • 感谢您的评论,非常感谢您的帮助。

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


【解决方案1】:

解决了这个难题。问题根本不在 .net 核心或异常属性中。我正在为 dataManagers 和 dataAccess 实例使用拦截器,因此在我在其中一个实例中引发异常后,拦截器会包装该错误并将其作为正常结果返回,这会导致 OnResultExecuted 调用其中包含异常。

【讨论】:

    猜你喜欢
    • 2012-03-11
    • 1970-01-01
    • 1970-01-01
    • 2018-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-19
    • 1970-01-01
    相关资源
    最近更新 更多