【问题标题】:Throw new exception with a code and a message使用代码和消息引发新异常
【发布时间】:2014-06-12 16:53:27
【问题描述】:

我正在从包含 statusCodestatusMessage 的服务器解析 JSON...我如何将这些扔到我的异常中以便我不必使用 if -我的捕获中的陈述?这样我就可以有一个通用的进程来处理所有exc.Codeexc.Message,而无需寻找它。

这是我的投球

else if (statusCode.Equals(26) && statusMessage.StartsWith("response sent", StringComparison.OrdinalIgnoreCase))
    throw new Exception("Response sent - 26");
else if (statusCode.Equals(0))
    throw new Exception("Fatal exception - 0");
else if (statusCode.Equals(3))
    throw new Exception("Invalid parameters - 3");
else if (statusCode.Equals(24))
    throw new Exception("Incorrect response Id - 24");

这是我的收获

try
{
    dataResponse = GetStatus.RequestStatus(httpRequest);
}
catch (Exception exc)
{
    if (exc.Message.ToString() == "Response sent - 26")
    {
        string errorCode = "26";
        string errorMessage = "Response Sent";
        // do things with erroCode and errorMessage...
    }
    else if (exc.Message.ToString() == "Fatal exception - 0")
    {
        string errorCode = "0";
        string errorMessage = "Fatal exception";
        //do things with errorCode and errorMessage...
    }
    // else ifs else ifs etc.. etc...
}
finally
{
    // do things
}

【问题讨论】:

    标签: c# exception-handling try-catch throw


    【解决方案1】:

    Exception 类上有一个 Data 属性。您可以将您的数据添加到其中。

    它实现了IDictionary...只需将您的键/值对添加到其中,如下所示:

    var ex = new Exception(string.Format("{0} - {1}", statusMessage, statusCode));
    ex.Data.Add(statusCode, statusMessage);  // store "3" and "Invalid Parameters"
    throw ex;
    

    然后在您的catch 块中读回它。 KeyValue 都是 object 类型,因此您必须将它们转换回原来的类型。

    catch (Exception exc)
    {
        var statusCode = exc.Data.Keys.Cast<string>().Single();  // retrieves "3"
        var statusMessage = exc.Data[statusCode].ToString();  // retrieves "Invalid Parameters"
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-16
      • 1970-01-01
      • 2018-05-05
      • 2021-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多