rest - Powershell正在吞噬REST错误响应

标签 rest powershell error-handling swallowed-exceptions

我在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

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

最佳答案

分为两个部分。首先,您需要使用-ErrorAction Stop引发终止错误。然后,我们可以使用try/catch块来捕获异常。有了Exception,我们就可以获取存储在Exception Status Description中的详细响应。这对于大多数请求都很好。

要获取邮件的正文,还需要执行几个步骤。由于我们得到了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
}

关于rest - Powershell正在吞噬REST错误响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56600792/

相关文章:

PowerShell计算错误

powershell - 使用Powershell在每行的开头添加文本

c# - 使用自定义错误页面捕获错误

.net - 如何解决 "InvalidOperationException:operation must have a single parameter whose type is Stream"

Powershell 安装 - 未找到指定搜索条件和模块名称的匹配项

web-services - GET 休息服务中的 DELETE 操作

python - 在Django中使用计数功能获取数据

ruby-on-rails - 用于 Rails 中带参数的 Flash 消息的 I18n

java - Spring Rest PostMapping 从 json 映射到多个表

rest - 如何在 IntelliJ IDEA 中使用 "Test restful web service"选项测试 RESTful Web 服务