使用代码和消息抛出新异常

Kyl*_*yle 4 c# exception-handling try-catch throw

我正在从包含statusCodestatusMessage... 的服务器解析JSON 我如何在我的异常中抛出这些,以便我不必if在我的catch中使用-statements?所以,我可以有一个通用的过程,处理所有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");
Run Code Online (Sandbox Code Playgroud)

这是我的捕获

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
}
Run Code Online (Sandbox Code Playgroud)

Gra*_*ICA 8

班上有一处Data房产Exception.您可以将数据添加到该数据中.

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

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

然后在你的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"
}
Run Code Online (Sandbox Code Playgroud)