rest - Invoke-RestMethod 的错误处理 - Powershell

标签 rest http error-handling 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

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

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

最佳答案

这有点尴尬,但据我所知,这是唯一的方法,无需执行更复杂的操作,例如使用 .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
}

关于rest - Invoke-RestMethod 的错误处理 - Powershell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29613572/

相关文章:

c# - 如何在 C# 中使用 SharePoint Online 2013 Rest API 删除列表项

api - 如何在 Artifactory 中获取 Artifact 的属性

python - 除了在尝试了try block 和程序的其余部分之后总是抛出 block 之外?

javascript - 使用 angular js 和 $http 请求登录不起作用

http - http.Server 的奇怪行为 - 为每个客户端建立三个连接?

http - 为什么 URL 和查询字符串部分的编码不同?

actionscript-3 - 如何在 Adob​​e Flex 3 中通过 HTTP 服务发送数组

sql - 如何在SQL查询中不获取数据消息

java - setVisible(true/false)错误JFrame

android - Firebase 中的对象版本控制