【问题标题】:how to pass an error message back before an exception is thrown如何在抛出异常之前将错误消息传回
【发布时间】:2020-05-19 06:08:50
【问题描述】:

我有以下收到错误消息的代码。我想在抛出异常之前将其传递到字符串中,这是我的代码

ValidateError(authDeserialized, "Succeed", "error", "failed"); //the validateError is a function as indicated below
Model.Response= authResponse.Content;

 protected static void ValidateError(dynamic response, string validStatus,string categoryMatch, string message)
        {  
            if (response.result.status != validStatus)
            {
                try
                {
                    var category = response.result.category;
                    if (category == categoryMatch)
                          message=ErrorCodes.MessageFor(code,description);
      //so i get the message back fine here but now how do i pass it back to this line   Model.Response= authResponse.Content; so that it can get saved?
                }
                catch (Exception) { }
                throw new Exception(message ?? "Request was not successfull");
            }
        }

【问题讨论】:

  • 可以在ValidateError 消息中访问authResponse 吗?如果是,则在构建该错误消息或在catch 块中分配它。您想将错误消息分配给authResponse 并且还想抛出错误,对吗?
  • @PrasadTelkikar 在 ValidateError 中无法访问 authResponse。是的,我想将错误消息分配给 autResponse.content
  • 嗨@PrasadTelkikar 它不返回消息它只是抛出异常而不返回消息
  • 它不会返回消息,但更新的错误消息将存储在消息变量中。您是否阅读了out 参数的文档并检查了我的答案。我建议您先阅读文档,根据我的回答更改您的代码,然后再进行调试。 Answer 不会返回任何消息,但会更新存储在failureMessage 中的错误消息

标签: c# error-handling try-catch


【解决方案1】:

由于您已经将message 发送到ValidateError() 方法,将该参数作为out parameter 传递,如果您为其分配新值,它将更新message 的值,然后它将更新消息并将外部环境可访问。

string failureMessage = "failed";
ValidateError(authDeserialized, "Succeed", "error", out failureMessage);
                                                  //^^^ This is what you have to change
//Now you can assign failureMessage to any other value
Model.Response= authResponse.Content;

protected static void ValidateError(dynamic response, string validStatus,string categoryMatch, out string message)
{                                                                                            //^^^ This is what you have to change
      if (response.result.status != validStatus)
      {
          try
          {
               var category = response.result.category;
               if (category == categoryMatch)
                   message=ErrorCodes.MessageFor(code,description);    //so i get the message back fine here but now how do i pass it back to this line   Model.Response= authResponse.Content; so that it can get saved?
          }
          catch (Exception) { }
          throw new Exception(message ?? "Request was not successfull");
      }
}

通过这种方式,您可以在抛出错误之前为失败消息赋值。

Try out online

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-01
    • 2014-03-15
    • 2011-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多