我有以下自定义异常:
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 的异常是否被包装,我该如何避免它?