从异步方法中捕获自定义异常

10

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

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吗? - Stuart
捕获的异常类型是什么?它可能是一个“AggregateException”,其中可能包含您的“CustomException”。 - Dave Becker
1个回答

12
问题在于Wait抛出的是AggregateException,而不是您试图捕获的异常。
您可以使用以下方法:
try
{
    var t = Task.Run(TestAsync);
    t.Wait();
}
catch (AggregateException ex) when (ex.InnerException is CustomException)
{
    throw;
}
catch (Exception)
{
    //handle exception here
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接