Cannot catch "proxy block page" error with Invoke-RestMethod / Try Catch ignored

123 views Asked by At

I am utilising Azure Instance Metadata Service API. This will only work on an Azure VM, which is fine, but I want some error handling. The trouble is that when I run this on my development laptop (heavily locked down environment), I get our corporate proxy block page and nothing I try (no pun intended) will catch the block page and thus handle the error.

It is like the proxy intercepts the request before Invoke-RestMethod can do anything.

Is there any way to catch the block message?

try
{
    $oRequest = Invoke-RestMethod -Headers @{"Metadata"="true"} -Method GET -Uri "http://169.254.169.254/metadata/instance?api-version=2020-06-01"
}
catch [System.Net.WebException]
{
    Throw "An error has occurred: $($_.exception.Message)"
}

$oRequest is empty and even piping to Out-Null doesn't stop the proxy block page message.

I appreciate this is really difficult to troubleshoot outside my corporate environment, but I am hoping someone may have experienced this behaviour and have a way of capturing the error.

The best I can come up with is a test to see if $oRequest is empty and handle that, but this doesn't seem right and it still shows the block message in the PS console.

PowerShell version 7

T. I. A

1

There are 1 answers

1
PowerShellGuy On

Well, the reason you're getting the error is because you're catching the original error, then forcing another to occur by using throw. You already caught it, no need to throw another error. You can't pipe a throw to out-null because there is nothing to send to the pipeline.

Also, though it may not be necessary at all times, it's good practice to -ErrorAction Stop on cmdlets that you wish to catch errors for.

try
{
    #This is where the exception will be thrown
    $oRequest = Invoke-RestMethod -Headers @{"Metadata"="true"} -Method GET -Uri "http://169.254.169.254/metadata/instance?api-version=2020-06-01" -ErrorAction Stop
}
catch [System.Net.WebException] #this catches the error that was thrown above and applies it to the built-in variable $_ for the catch's scope
{
    #if you uncomment the throw line, notice how you don't reach the next line,
    #this is because it creates a terminating error, and it's not handled with a try/catch
    #throw "bananas"
    $banana = "An error has occurred: $($_.exception.Message)"
}
Write-Host $banana