Invoke-RestMethod的错误处理 - Powershell

use*_*230 21 rest error-handling http powershell-4.0

我有一个使用Skytap API(REST)的powershell脚本.我想抓住错误,如果有错误,并尝试显示它.

例如,我们正在改变IP:

Invoke-RestMethod -Uri https://cloud.skytap.com/configurations/XXXXXX/vms/YYYYYY/interfaces/ZZZZZZ?ip=10.0.0.1 -Method PUT -Headers $headers
Run Code Online (Sandbox Code Playgroud)

如果在其他地方使用IP,我将得到409冲突错误(请求格式正确,但与其他资源或权限冲突).

我想检查错误是否为409,然后告诉它做一些其他事情.

Dav*_*son 53

这有点尴尬,但据我所知,只有使用.NET的WebRequest和ConvertFrom-Json(或者您期望的任何数据格式)做一些更复杂的事情,这是唯一的方法.

try {
    Invoke-RestMethod ... your parameters here ... 
} catch {
    # Dig into the exception to get the Response details.
    # Note that value__ is not a typo.
    Write-Host "StatusCode:" $_.Exception.Response.StatusCode.value__ 
    Write-Host "StatusDescription:" $_.Exception.Response.StatusDescription
}
Run Code Online (Sandbox Code Playgroud)

  • 您不必将 `$_.Exception` 分配给不同的变量,除非您尝试在 `catch` 块之外或从 `$_` 具有不同含义的代码中访问它(例如在传递的脚本块中)到 `Where-Object`、`ForEach-Object` 等)。在这种情况下,“Exception”参数的类型为“System.Net.WebException”,因此有关该类型的任何文档都将是相关的。另外值得注意的是,我的示例代码有点过于简单。在生产代码中,您需要考虑不同“异常”类型的可能性,但我觉得这超出了这个问题的范围。 (2认同)

MeG*_*Guy 12

我知道您要求使用 Powershellv4,但从 v6/v7 开始:

Try {
     $WebRequestResult = Invoke-RestMethod -Uri $URL -Headers $Headers -Body $BodyJSON -Method $Method -ContentType $ContentType -SkipCertificateCheck
} Catch {
    if($_.ErrorDetails.Message) {
        Write-Host $_.ErrorDetails.Message
    } else {
        Write-Host $_
    }
}
Run Code Online (Sandbox Code Playgroud)


Joh*_*ohn 12

Powershell 7 引入了-SkipHttpErrorCheck参数。这指示 cmdlet 的行为方式与编程框架中的 Web 请求类似(即,其中 404、409 等是有效响应 - Web 请求成功,但服务器返回错误代码)。

这可以与-StatusCodeVariable参数结合使用。这指示 cmdlet 将响应代码插入到变量中。但是,变量名称作为字符串传递(而不是作为引用)。例如:

$scv = $null
Invoke-RestMethod ... -SkipHttpErrorCheck -StatusCodeVariable "scv"
Run Code Online (Sandbox Code Playgroud)