nancy
nancy

Reputation: 99

PowerShell 400 Bad Request Response Body

I'm trying print response body after getting status 400.

try {
    if ($Responses = (Invoke-WebRequest @Param -ErrorAction Stop)) {
        $StatusCodes = $([int]$Responses.BaseResponse.StatusCode)
    }
    Write-Host ("State code : " + $StatusCodes)
} catch [System.Net.WebException] {
    $StatusCodes = $_.Exception.Response.StatusCode.Value__;
    $Messages = (($_.ErrorDetails.Message) | ConvertFrom-Json).Message;
    Write-Host ("State code : " + $StatusCodes);
    Write-Host ("Message: " + $Messages)
}

My code is working for only status code. I want print error response body

{
    "status": "Failed",
    "warnings": {
        "errorCode": ",
        "errorDesc": " "
    }
}

Upvotes: 0

Views: 410

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200193

The error response doesn't have the kind of body you seem to expect. If you want something like that you need to build it yourself.

try {
    ...
} catch [Net.WebException] {
    [PSCustomObject]@{
       'status'   = 'Failed'
       'warnings' = @{
           'errorCode' = $_.Exception.Response.StatusCode.value__
           'errorDesc' = $_.Exception.Message
       }
    } | ConvertTo-Json
}

Upvotes: 1

Related Questions