Powershell正在吞噬REST错误响应
我正在Powershell中使用Powershell正在吞噬REST错误响应,rest,powershell,error-handling,swallowed-exceptions,Rest,Powershell,Error Handling,Swallowed Exceptions,我正在Powershell中使用Invoke WebRequest,当目标API端点确定我的请求无效时,它显然会拒绝该请求并发回HTTP错误代码,如(400)Bad request,但它还包括错误原因(由API供应商提供)但PowerShell内部的日志中不包括这一点 我确认详细的错误被发回了,因为我在邮递员和供应商中看到了它。Powershell只是不想展示它。下面是我的代码及其生成的响应的示例 Invoke-WebRequest -Credential $cred -Uri $url -Me
Invoke WebRequest
,当目标API端点确定我的请求无效时,它显然会拒绝该请求并发回HTTP错误代码,如(400)Bad request
,但它还包括错误原因(由API供应商提供)但PowerShell内部的日志中不包括这一点
我确认详细的错误被发回了,因为我在邮递员和供应商中看到了它。Powershell只是不想展示它。下面是我的代码及其生成的响应的示例
Invoke-WebRequest -Credential $cred -Uri $url -Method POST -Body $json -ContentType 'application/json'
如何捕获更详细的错误消息?本文由两部分组成。首先,您需要让它抛出一个终止错误
-ErrorAction Stop
。这允许我们使用try/catch块捕获异常。对于异常,我们可以获得存储在异常状态描述中的详细响应。这对于大多数请求来说都很好
要获得消息的正文,还需要几个步骤。因为我们得到了一个对象,所以我们没有“好”的消息参数。因此,我们必须使用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
仍然缺少关于请求中哪些特定失败的更详细部分请参见上面的编辑。要获取正文的内容,需要添加一个StreamReader来读取数据。就是这样!我刚刚在最后一行添加了.message
,以获取我想要的内容。非常感谢!!!
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
}