抛出异常的两种方法如何区分它们

时间:2018-01-29 00:07:09

标签: c# exception-handling

我有一个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");
}

1 个答案:

答案 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

然后修改您的方法以改为抛出这些描述性错误。