【问题标题】:How to use variable to store error type for catch block?如何使用变量来存储 catch 块的错误类型?
【发布时间】:2019-07-04 09:32:02
【问题描述】:

我想为脚本中的每个命令处理异常。为此,我正在为try..catch 编写一个函数。该函数有两个参数:$command,要执行的命令,和$errorTypecatch 块中指定的可选错误类型。

function tryCatch ($command, $errorType) {
    try {
        $command
    } catch [$errorType] {
        # function to be called if this error type occurs
        catchError
    }
}

但是我不知道如何将错误类型作为变量传递给 catch 块。我收到此错误:

在 \script.ps1:233 字符:25 + 尝试 {$command} 捕获 [$errorType] {catchError} + ~ '[' 后缺少类型名称。

我试图绕过它,但似乎没有任何效果。有没有办法做到这一点?

【问题讨论】:

    标签: powershell error-handling exception-handling try-catch


    【解决方案1】:

    我认为您不能使用变量来指定要捕获的类型。您可以做的是在 catch 块内使用条件:

    function Invoke-Something($command, [Object]$errorType) {
        try {
            $command
        } catch {
            if ($_.Exception -is $errorType) {
                catchError
            } else {
                # do something else
            }
        }
    }
    
    Invoke-Something 'whatever the command' ([System.IO.IOException])
    

    【讨论】:

      【解决方案2】:

      简短的回答,我不相信你能做你想做的事。让我演练只是为了确保我理解场景。

      catch 块的参数是一种或多种异常类型,例如System.Net.WebException

      try {
         $wc = new-object System.Net.WebClient
         $wc.DownloadFile("http://www.contoso.com/MyDoc.doc")
      } catch [System.Net.WebException], [System.IO.IOException] {
          "Unable to download MyDoc.doc from http://www.contoso.com."
      } catch {
          "An error occurred that could not be resolved."
      }
      

      说这只是为了水平设置。

      现在,我们通常会看到这些类型是硬编码的,但您希望将 catch 块中的类型作为变量动态分配:

      try {
         ...
      } catch $exceptionType {
         catchError
      }
      

      问题是 catch 后面需要跟一个异常类型而不是一个变量。该变量将(如果它承载异常类型)属于 RuntimeType 类型。您可以尝试使用 GetType() 或类似的方法从变量中找出异常类型。 Net-net,它就是行不通。

      在您的脚本函数中放置一个通用的 catch 块(没有类型),然后将值传递给您的 catch 函数,并让其中的分支逻辑执行您想做的任何事情。

      try { ... } catch { catchError -Command $command -Exception $_ }
      

      而且,如果你不想传递整个异常对象,你可以使用...

      $_.FullyQualifiedErrorId
      

      【讨论】:

      • 是的,你理解我想要做什么是正确的。感谢您提供非常有用的信息,并准确解释了为什么我正在尝试做的事情不起作用。
      猜你喜欢
      • 2019-02-19
      • 1970-01-01
      • 1970-01-01
      • 2016-05-04
      • 1970-01-01
      • 2011-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多