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

c# – 使用代码和消息抛出新异常,第1张

概述我正在从包含statusCode和statusMessage的服务器解析 JSON …如何在我的异常中抛出这些,以便我不必在catch中使用if-statements?这样我就可以拥有一个处理所有exc.Code和exc.Message的通用进程,而无需查找它. 这是我的投掷 else if (statusCode.Equals(26) && statusMessage.StartsWith("r 我正在从包含statusCode和statusMessage的服务器解析 JSON …如何在我的异常中抛出这些,以便我不必在catch中使用if-statements?这样我就可以拥有一个处理所有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}
解决方法 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块中读回来. Key和Value都是类型对象,因此您必须将它们转换回原始类型.

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

以上是内存溢出为你收集整理的c# – 使用代码消息抛出新异常全部内容,希望文章能够帮你解决c# – 使用代码和消息抛出新异常所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/langs/1219004.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-05
下一篇2022-06-05

发表评论

登录后才能评论

评论列表(0条)

    保存