c# - 如何在引发异常之前将错误消息传递回

标签 c# error-handling try-catch

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

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");
            }
        }

最佳答案

由于您已经将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

关于c# - 如何在引发异常之前将错误消息传递回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60040024/

相关文章:

c# - 确定 Windows 窗体应用程序中的插入模式

php - 我从PHP应用程序中收到以下警告,我想知道如何修复它: [duplicate]

c++ - 将 fstream 数据写入磁盘时如何检测 fatal error ?

javascript - 在 try catch 操作期间*究竟*发生了什么?

c# - ASP.NET 核心 : Custom validation

c# - 使用 FindControl() 查找控件

PHP:trim() 不适用于两个变量

C++ 成功 `try` 分支

exception - 从 Perl 6 中的异常处理程序返回值

c# - System.Windows.Controls.Canvas 到 System.Windows.Controls.TextBox 的无效转换异常