我有一个try catch块,它包含两个可以抛出ArgumentException的方法。
我想区分异常,以便我可以为用户返回更好的错误消息。 最好的方法是什么? (我想避免用两个独立的try catch块来包围它。)
try
{
var store = storeFactory.Create(id); // Can Throw ArgumentException
var order = await store.GetOrderAsync(orderId); //Can Throw ArgumentException
return Ok(order);
}
catch (ArgumentException ex)
{
//TODO: How To Tell Which Methods Throw The Exception (Create Or GetOrderAsync)
return NotFound("Store Id Was Not Found");
return NotFound("Order Id Was Not Found");
}
答案 0 :(得分:2)
您只需将try
块分成两个try
块:
try
{
var store = storeFactory.Create(id); // Can Throw ArgumentException
try
{
var order = await store.GetOrderAsync(orderId); //Can Throw ArgumentException
return Ok(order);
}
catch ( ArgumentException ex )
{
return NotFound("Order Id Was Not Found");
}
}
catch (ArgumentException ex)
{
//TODO: How To Tell Which Methods Throw The Exception (Create Or GetOrderAsync)
return NotFound("Store Id Was Not Found");
}
然而,更好的解决方案是为两种情况创建一种新类型的例外,例如:
public class OrderNotFoundException : Exception
和
public class StoreNotFoundException : Exception
然后修改您的方法以改为抛出这些描述性错误。