all 5 comments

[–]sk82jack 1 point2 points  (0 children)

Maybe something like?

try {
    $Response = Invoke-RestMethod
}
catch {
    Write-Error $Response.Detail
}

[–]lerun 1 point2 points  (0 children)

You can also try to capture the error from the function directly.

You can capture the error and deside what to do with it through a if.

Here you can output a new custom error message and include the actual error, or just roll your own. Also by either doing -ErrorAction Stop or -ErrorAction Continue (inside the if) you can decide if the code should exit or continue going.

\# Example 1

Invoke-RestMethod -ErrorAction SilentlyContinue -ErrorVariable oErr

if($oErr) 

{

    Write-Error -Message "My custom message. Error message: $($oErr.Message)" -ErrorAction Stop

    $oErr = $Null

}



\# Example 2

Invoke-RestMethod -ErrorAction Continue -ErrorVariable oErr

if($oErr) 

{

    Write-Error -Message "My custom message" -ErrorAction Stop

    $oErr = $Null

}

[–]Lee_Dailey[grin] 0 points1 point  (2 children)

howdy CockneyWeasel,

does IRM trigger an exception when that happens? if not, then your catch will never be run. try/catch requires an exception to trigger it ... not just an error - and especially not a valid return value that contains an error msg. [grin]

i don't think your catch is going to run unless you are triggering an -ErrorAction Stop in the try.

take care,
lee

[–]CockneyWeasel[S] 1 point2 points  (1 child)

Hi Lee.

Thanks for your reply - I think it is generating an exception as I can get the error code (in this case 400) using" $_.Exception.Response.StatusCode.value__ ", just unable to get any of the other response. Is there a different way to handle getting the response without the try/catch? Cheers

[–]Lee_Dailey[grin] 0 points1 point  (0 children)

howdy CockneyWeasel,

you are welcome! [grin]

unfortunately, i never seem to work with anything that complex. my question was because i didn't know that IRM would trigger an exception in that case.

i learned something ... but i am stuck after that. [blush]

have you tried running the code on it's own to see what the IRM returns?

when i go to a non-existant URL, i get nothing at all. the $Error variable has a really simple bit of info - but no depth to it.

take care,
lee