【发布时间】: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 属性以查找预期的异常。
-
请发布一个最小的、可重现的示例。在使用
Result和Wait()等阻塞方法时看到AggregateException包装器是正常的,但在使用await时则不会。
标签: c# exception aggregateexception