【发布时间】:2017-10-18 11:27:48
【问题描述】:
假设我有一个 Web API 服务,它调用我的用户服务来返回用户个人资料信息等。
UserProfileService 可以抛出 UserNotFoundException。抛出时,它会被序列化并作为AggregateException 中的内部异常发送,可以在调用方法中捕获。此服务使用 Service Fabric 的远程服务进行 RPC。
我的 WebAPI 像这样调用我的服务:
[HttpGet]
public async Task<IActionResult> Get(int id)
{
try
{
var profile = await _userService.GetProfileAsync(int id);
return Json(profile);
} catch (AggregateException ae)
{
// Here I want to call NotFound() if `UserNotFoundException`
// was thrown, otherwise...
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
这里有几个问题:
- 如何处理预期的异常?
天真地我会做这样的事情:
try { /* ... */ } catch (AggregateException ae)
{
foreach(var e in ae.InnerExceptions)
{
if (e is UserNotFoundException)
{
return NotFound();
}
}
return errorResponse ?? StatusCode(StatusCodes.Status500InternalServerError);
}
但问题是,如果有多个例外,只有一个会“获胜”。而且,我相信 - 尽管不能保证,最早添加的 Exceptions 将具有优先权,因为它们在 InnerExceptions 中的索引较低。我是不是在想这个,这个解决方案会好吗?我的自定义异常只有在我知道应该被抛出时才会被抛出,对吗?
这引出了我的另一个问题:
- 在什么情况下,您会在
AggregateException中检索多个异常。
当你有Task a调用Task b调用Task c,c抛出,b不抛出,a抛出时,你会得到包含a和的聚合异常c 的例外情况?
【问题讨论】:
标签: c# exception-handling asp.net-core azure-service-fabric