Why is my custom exception wrapped by an AggregatException. What does this depend on?

869 Views Asked by At

I have the following custom exception :

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

    }

I throw it at this point:

 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;
        }

But when testing, I find that it is wrapped by an AggregateException, the test fails:

 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)

At other places in the same class I throw it too (for example in the method SampleMethod() that calls AquireToken() and, there I only get the custom exception.

I am confused, because in other projects I do supposedly analogous and there the exceptions are not wrapped....

What does it depend on, if the exception of AggregateException is wrapped or not, how can I avoid it?

1

There are 1 best solutions below

0
SmartCoder On

You are starting a task here by using await/aync and you are not handling exception. That is why you are getting aggregate exception. From MS docs

https://learn.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);
        });