0

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>
ubienewbie
  • 1,771
  • 17
  • 31
  • $rv is the result written to stdout. You want to also capture stderr OR write stderr to stdout. This question will help: https://stackoverflow.com/questions/24222088/capture-program-stdout-and-stderr-to-separate-variables or this one: https://stackoverflow.com/questions/8761888/capturing-standard-out-and-error-with-start-process – John Hanley Sep 13 '21 at 06:57

1 Answers1

0

Thank you John Hanley. Posting your suggestions as answer to help other community members.

As you $rv is the result written to stdout and you want to capture stderr.

The data from stdout will be strings while stderr produces System.Management.Automation.ErrorRecord objects.

```swift
$allOutput = & myprogram.exe 2>&1
$stderr = $allOutput | ?{ $_ -is [System.Management.Automation.ErrorRecord] }
$stdout = $allOutput | ?{ $_ -isnot [System.Management.Automation.ErrorRecord] }
```  

and, If you want to capture standard out and error with start process without sending to file.

Start-Process
     [-FilePath] <String>
     [[-ArgumentList] <String[]>]
     [-Credential <PSCredential>]
     [-WorkingDirectory <String>]
     [-LoadUserProfile]
     [-NoNewWindow]
     [-PassThru]
     [-RedirectStandardError <String>]
     [-RedirectStandardInput <String>]
     [-RedirectStandardOutput <String>]
     [-WindowStyle <ProcessWindowStyle>]
     [-Wait]
     [-UseNewEnvironment]
     [-WhatIf]
     [-Confirm]
     [<CommonParameters>]

Check Start Process document for better understanding.

Also check the SO1 and SO2 with related information.

SaiSakethGuduru
  • 2,218
  • 1
  • 5
  • 15