gpt4 book ai didi

c# - 抛出带有代码和消息的新异常

转载 作者:太空狗 更新时间:2023-10-30 00:31:44 24 4
gpt4 key购买 nike

我正在从包含 statusCodestatusMessage 的服务器解析 JSON...我如何将它们抛出到我的异常中,这样我就不会 必须在我的 catch 中使用 if 语句?这样我就可以拥有一个通用流程来处理所有 exc.Codeexc.Message,而无需查找。

这是我的 throw

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
}

最佳答案

有一个 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;

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

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

关于c# - 抛出带有代码和消息的新异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23319137/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com