0

我有以下自定义异常:

 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)

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

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

它取决于什么,如果 AggregateException 的异常是否被包装,我该如何避免它?

4

1 回答 1

0

您正在使用 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);
        });
于 2021-11-05T11:29:48.137 回答