【问题标题】:Why is my custom exception wrapped by an AggregatException. What does this depend on?为什么我的自定义异常被 AggregatException 包裹。这取决于什么?
【发布时间】:2021-11-05 11:04:16
【问题描述】:

我有以下自定义异常:

 public class MyCustomException : Exception
    {
        public MyCustomException(string message) : base(message)
        { }

    }

此时我就扔了:

 private async Task<string> AquireToken()
        {
            string url = GetUrl("authentication/connect/token");
           
//...
 private static string GetUrl(string relativeUrl)
        {
            var baseUrl = Environment.GetEnvironmentVariable("BASE_URL");
            if (string.IsNullOrEmpty(baseUrl))
            {
                throw new MyCustomException("Address is not set in Enviroment Variable (BASE_URL)");
            }
            var fullUrl = $"{baseUrl.Trim('/')}/{relativeUrl}";
            return fullUrl;
        }

但是在测试的时候,发现被AggregateException包裹,测试失败:

 MyCustomException exception = await Assert.ThrowsAsync<MyCustomException>(async () =>
            {
                Environment.SetEnvironmentVariable("BASE_URL", null);
                await serviceUnderTest.SampleMethod(input);
            });
Assert.Throws() Failure
Expected: typeof(SAMPLECOMPANY.SAMPLEPROJECT.SampleMicroservice.WebApi.Service.Exceptions.MyCustomException)
Actual:   typeof(System.AggregateException): One or more errors occurred. (Address is not set in Enviroment Variable (BASE_URL))
---- System.AggregateException : One or more errors occurred. (Address is not set in Enviroment Variable (BASE_URL))
-------- SAMPLECOMPANY.SAMPLEPROJECT.SampleMicroservice.WebApi.Service.Exceptions.MyCustomException : Address is not set in Enviroment Variable (BASE_URL)

在同一类的其他地方,我也抛出它(例如在调用 AquireToken() 的方法 SampleMethod() 中,我只得到自定义异常。

我很困惑,因为在其他项目中我应该是类似的,并且没有包装异常......

这取决于什么,AggregateException的异常是否被包裹,如何避免?

【问题讨论】:

  • docs.microsoft.com/en-us/dotnet/api/… -> 从代码来看,您的单元测试框架似乎正在这样做
  • 在您的测试代码中,您调用的是SampleMethod。它与您的AquireToken 方法有何不同?
  • @PeterCsala AquireToke 被 SampleMethod 调用
  • 这是 Task 的行为,它运行的代码中引发的任何异常都会被 AggregateException 包装。迭代其 InnerExceptions 属性以查找预期的异常。
  • 请发布一个最小的、可重现的示例。在使用 ResultWait() 等阻塞方法时看到 AggregateException 包装器是正常的,但在使用 await 时则不会。

标签: c# exception aggregateexception


【解决方案1】:

您正在使用 await/aync 在这里开始一个任务并且您没有处理异常。这就是为什么你会得到聚合异常。来自 MS 文档

https://docs.microsoft.com/en-us/dotnet/api/system.aggregateexception.handle?view=netframework-4.7.2

 MyCustomException exception = await Assert.ThrowsAsync<MyCustomException>(async () =>
        {
            Environment.SetEnvironmentVariable("BASE_URL", null);
            await serviceUnderTest.SampleMethod(input);
        });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-20
    • 2020-02-20
    • 1970-01-01
    相关资源
    最近更新 更多