Powershell: invoke-webrequest unhandled exception on 404

Created on 28 Feb 2019  路  9Comments  路  Source: PowerShell/PowerShell

Area-Cmdlets-Utility Issue-Question Resolution-Answered

All 9 comments

steps:
request a file not on server from *.vod.com (see powershell transcript)
404 info is returned in stdlist (or stderr),
stack trace in -errorvariable output
no results returned into return variable (i.e. $returnvar=invoke-webrequest ...)

expected to be able to see $returnvar.statuscode =404
inspecting the returned header, you can see:
server | AmazonS3
x-cache | Error from cloudfront

'
---> Microsoft.PowerShell.Commands.HttpResponseException: Response status code does not indicate success: 404 (Not Found).
at System.Management.Automation.MshCommandRuntime.ThrowTerminatingError(ErrorRecord errorRecord)
--- End of inner exception stack trace ---
1.txt
'

@qt3m45su0najc7 Please use issue template to push issue.

/cc @markekraus Could you please look the issue?

This is By Design. A non-success HTTP status message throws terminating errors and does not return any output. You must do something like this:

try {
    $response = invoke-WebRequest -Uri $Uri -ErrorAction Stop
    $StatusCode = $Response.StatusCode
} catch {
    $StatusCode = $_.Exception.Response.StatusCode.value__
}

Ok, @markekraus , but I did mention that the $response= returns nothing, so there is no $response.statuscode to evaluate. Please confirm using the example in the transcript or fake one for that domain to verify.

@qt3m45su0najc7

you can use what i posted before:

$Uri = 'https://img.vod.com/secret_recipe.jpg'
try {
    $response = invoke-WebRequest -Uri $Uri -ErrorAction Stop
    $StatusCode = $Response.StatusCode
} catch {
    $StatusCode = $_.Exception.Response.StatusCode.value__
}

$Response will not be fully populated unless you get a success code (e.g. 200). However, you can process the $_.Exception.Response in the catch{} block which is a System.Net.Http.HttpResponseMessage object.

In my example, $StatusCode = $Response.StatusCode will be hit when the status is successful and $StatusCode = $_.Exception.Response.StatusCode.value__ will be hit when it is not and in the end, $StatusCode will have the status code regardless of whether the request was successful or not.

In other words, you need to write your code in such a way to handle the errors as $Response will not be populated when a non-succes status message is returned.

@markekraus works as you advertised. Thank you.

@markekraus I imagine this scenario might be common enough that perhaps adding that example to the docs page may be warranted? 馃檪

@vexx32 If you think so, please open an issue in PowerShell/PowerShell-Docs

Was this page helpful?
0 / 5 - 0 ratings