【问题标题】:Powershell is swallowing REST error responsePowershell 正在吞噬 REST 错误响应
【发布时间】:2019-06-14 15:02:27
【问题描述】:

我在 Powershell 中使用Invoke-WebRequest,每当我的请求被目标 API 端点确定为无效时,它显然会拒绝该请求并发送回一个 HTTP 错误代码,如(400) Bad Request,但它也包括原因错误(由 API 供应商提供),但未包含在 PowerShell 内的日志中。

我确认详细错误已发回,因为我在 PostMan 中看到了它,并且供应商也确认了这一点。 Powershell 只是不想展示它。这是我的代码及其生成的响应的示例。

Invoke-WebRequest -Credential $cred -Uri $url -Method POST -Body $json -ContentType 'application/json'
Invoke-WebRequest : The remote server returned an error: (400) Bad Request.
At \\*****\******$\Appsense\Desktop\Untitled2.ps1:42 char:1
+ Invoke-WebRequest -Credential $cred -Uri $url -Method POST -Body $jso ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) 
    [Invoke-WebRequest], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands. 
   InvokeWebRequestCommand

如何捕获更详细的错误消息?

【问题讨论】:

    标签: rest powershell error-handling swallowed-exceptions


    【解决方案1】:

    这两个部分。首先你需要让它抛出一个带有-ErrorAction Stop 的终止错误。这允许我们使用 try/catch 块来捕获异常。有了异常,我们就可以得到存储在异常状态描述中的详细响应。这适用于大多数请求。

    要获取邮件正文还需要几个步骤。因为我们得到一个WebResponse 对象,所以我们没有“Nice”消息参数。所以我们必须自己使用 StreamReader 来流式传输内容:

    try
    {
        $Response = Invoke-WebRequest -Credential $cred -Uri $url -Method POST -Body $json -ContentType 'application/json' -ErrorAction Stop
        # This will only execute if the Invoke-WebRequest is successful.
        $StatusCode = $Response.StatusCode
    }
    catch
    {
        #Excepion - Display error codes
        Write-Host "StatusCode:" $_.Exception.Response.StatusCode.value__ 
        Write-Host "StatusDescription:" $_.Exception.Response.StatusDescription
    
        #Get body of me
        $streamReader = [System.IO.StreamReader]::new($_.Exception.Response.GetResponseStream())
        $ErrResp = $streamReader.ReadToEnd() | ConvertFrom-Json
        $streamReader.Close()
        Write-Host $ErrResp
    }
    

    【讨论】:

    • 关闭!它返回 StatusCode: 400 StatusDescription: Bad Request 仍然缺少关于请求中具体失败的更详细的部分
    • 请参阅上面的编辑。要获取 Body 的内容需要在 StreamReader 中添加以读取数据。
    • 做到了!我刚刚在最后一行添加了.message 来获取我想要的内容。非常感谢!!!
    猜你喜欢
    • 1970-01-01
    • 2020-08-27
    • 1970-01-01
    • 2011-02-18
    • 2019-02-24
    • 1970-01-01
    • 1970-01-01
    • 2018-05-18
    • 2016-04-23
    相关资源
    最近更新 更多