【问题标题】:Catch custom exceptions from an async method从异步方法中捕获自定义异常
【发布时间】:2017-04-24 07:17:43
【问题描述】:

我试图捕获异步方法中抛出的自定义异常,但由于某种原因,它总是最终被通用异常捕获块捕获。请参阅下面的示例代码

class Program
{
    static void Main(string[] args)
    {
        try
        {
            var t = Task.Run(TestAsync);
            t.Wait();
        }
        catch(CustomException)
        {
            throw;
        }
        catch (Exception)
        {
            //handle exception here
        }
    }

    static async Task TestAsync()
    {
        throw new CustomException("custom error message");
    }
}

class CustomException : Exception
{
    public CustomException()
    {
    }

    public CustomException(string message) : base(message)
    {
    }

    public CustomException(string message, Exception innerException) : base(message, innerException)
    {
    }

    protected CustomException(SerializationInfo info, StreamingContext context) : base(info, context)
    {
    }
}

【问题讨论】:

  • 是因为它捕获了 AggregateException 吗?
  • 捕获的异常是什么类型的?它可能是一个AggregateException,其中可能包含您的CustomException

标签: c# .net


【解决方案1】:

问题在于Wait 抛出了一个AggregateException,而不是您试图捕获的异常。

你可以用这个:

try
{
    var t = Task.Run(TestAsync);
    t.Wait();
}
catch (AggregateException ex) when (ex.InnerException is CustomException)
{
    throw;
}
catch (Exception)
{
    //handle exception here
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-17
    • 2015-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-09
    • 1970-01-01
    相关资源
    最近更新 更多