加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 02:01:23 所属栏目:百科 来源:网络整理
导读:我正在从包含statusCode和statusMessage的服务器解析 JSON …如何在我的异常中抛出这些,以便我不必在catch中使用if-statements?这样我就可以拥有一个处理所有exc.Code和exc.Message的通用进程,而无需查找它. 这是我的投掷 else if (statusCode.Equals(26) s
我正在从包含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"
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读