是否有可能在动作过滤器上引发异常并赶上中间件?

时间:2019-02-07 08:14:21

标签: .net-core

[已解决]当我使用 IAsyncActionFilter 时,它会捕获。

我有一个 AuthorizeFilterAttribute 。当我在执行动作时抛出新异常时,我的中间件类不会捕获它,而会捕获其他异常。我如何捕获此异常?

public class AuthorizeFilterAttribute : IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext context)
    {
        throw new Exception();
    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
    }
}

我的错误处理中间件类。

public class ErrorHandlingMiddleware
{
    private readonly RequestDelegate _next;

    private readonly ILogger<ErrorHandlingMiddleware> _logger;

    /// <summary>
    /// Constructor
    /// </summary>
    /// <param name="next">The next method</param>
    /// <param name="logger">logging</param>
    public ErrorHandlingMiddleware(RequestDelegate next, ILogger<ErrorHandlingMiddleware> logger)
    {
        _next = next;
        _logger = logger;
    }

    /// <summary>
    /// Invocation next method with async
    /// </summary>
    /// <param name="context">Http request</param>
    /// <returns>Task object</returns>
    public async Task Invoke(HttpContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }

        var sw = Stopwatch.StartNew();

        try
        {
            await _next(context);
            sw.Stop();
        }
        catch (Exception exception)
        {

        }
    }
}

0 个答案:

没有答案