How can I catch and handle error responses from Azure CLI az rest command?
If I paste the following into my console (Powershell 7.1 running on Windows), I see some error text written to the console, but it doesn't actually throw which would enter the catch block, nor is anything written into $rv.
What am I missing here and how can I inspect the return value of az rest after an error?
try {
$rv = (az rest --method post --url "https://graph.microsoft.com/v1.0/servicePrincipals/$DELIBERATE_ERROR") #--body $body)
Write-Host "rv:"
$rv
}
catch {
Write-Host "error:"
$error
}
Note: I also saved the above in a file called Untitled-2.ps1 and ran it but you can just copy/paste it into console.
PS D:\code\Powershell> .\Untitled-2.ps1
ERROR: Bad Request({"error":{"code":"BadRequest","message":"Write requests (excluding DELETE) must contain the Content-Type header declaration.","innerError":{"date":"2021-09-13T06:02:39","request-id":"447b4cdc-cc43-4e38-a960-d389a3ea3a87","client-request-id":"447b4cdc-cc43-4e38-a960-d389a3ea3a87"}}})
rv:
PS D:\code\Powershell>