C# 使用代码和消息引发新异常

C# 使用代码和消息引发新异常,c#,exception-handling,try-catch,throw,C#,Exception Handling,Try Catch,Throw,我正在解析一个包含statusCode和statusMessage的服务器上的JSON。。。我如何在异常中抛出这些语句,以便不必在catch中使用if-语句?这样我就可以有一个通用的过程来处理所有的exc.code和exc.Message,而无需查找它 这是我的掷骰 else if (statusCode.Equals(26) && statusMessage.StartsWith("response sent", StringComparison.OrdinalIgnoreCa

我正在解析一个包含
statusCode
statusMessage
的服务器上的JSON。。。我如何在异常中抛出这些语句,以便不必在catch中使用
if
-语句?这样我就可以有一个通用的过程来处理所有的
exc.code
exc.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
}
异常
类上有一个属性。你可以把你的数据加到上面

它实现了
IDictionary
。。。只需向其中添加键/值对,如下所示:

var ex = new Exception(string.Format("{0} - {1}", statusMessage, statusCode));
ex.Data.Add(statusCode, statusMessage);  // store "3" and "Invalid Parameters"
throw ex;
然后在
catch
块中读取它。
都是
对象
类型,因此必须将它们转换回原始类型

catch (Exception exc)
{
    var statusCode = exc.Data.Keys.Cast<string>().Single();  // retrieves "3"
    var statusMessage = exc.Data[statusCode].ToString();  // retrieves "Invalid Parameters"
}
catch(异常exc)
{
var statusCode=exc.Data.Keys.Cast().Single();//检索“3”
var statusMessage=exc.Data[statusCode].ToString();//检索“无效参数”
}