Consider:
Invoke-WebRequest $sumoApiURL -Headers @{"Content-Type"= "application/json"} -Credential $cred -WebSession $webRequestSession -Method post -Body $sumojson -ErrorAction Stop
This throws the following exception:
How can I catch it entirely or at least filter out the "A resource with the same name already exist."?
Using $_.Exception.GetType().FullName
yields
System.Net.WebException
and $_.Exception.Message
gives
The remote server returned an error: (400) Bad Request.
This question is related to
powershell
exception
exception-handling
I keep coming back to these questions trying to figure out where exactly the data I'm interested in is buried in what is truly a monolithic ErrorRecord structure. Almost all answers give piecemeal instructions on how to pull certain bits of data.
But I've found it immensely helpful to dump the entire object with ConvertTo-Json
so that I can visually see LITERALLY EVERYTHING in a comprehensible layout.
try {
Invoke-WebRequest...
}
catch {
Write-Host ($_ | ConvertTo-Json)
}
Use ConvertTo-Json
's -Depth
parameter to expand deeper values, but use extreme caution going past the default depth of 2
:P
https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/convertto-json
I found it!
Simply print out $Error[0]
for the last error message.
You can add:
-ErrorVariable errvar
And then look in $errvar
.
The following worked well for me
try {
asdf
} catch {
$string_err = $_ | Out-String
}
write-host $string_err
The result of this is the following as a string instead of an ErrorRecord object
asdf : The term 'asdf' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\Users\TASaif\Desktop\tmp\catch_exceptions.ps1:2 char:5
+ asdf
+ ~~~~
+ CategoryInfo : ObjectNotFound: (asdf:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
Source: Stackoverflow.com