PowerShell 7.3 - implementing Reading JSON from REST API and Handling Errors Gracefully
I've tried everything I can think of but I'm working through a tutorial and I'm experimenting with I'm trying to make a REST API call using PowerShell 7.3 to fetch some JSON data, but I'm running into trouble when the API returns an behavior response... My goal is to read the JSON response, handle any errors properly, and parse the data correctly. Here's the code I've written so far: ```powershell $uri = 'https://api.example.com/data' $response = Invoke-RestMethod -Uri $uri -Method Get -ErrorAction Stop if ($response -is [System.Management.Automation.PSCustomObject]) { # Process the response $data = $response.data Write-Output "Data: $data" } else { Write-Output "Unexpected response type: $($response.GetType().Name)" } ``` The question arises when the API returns an behavior (for instance, a 404 or a 500). Instead of throwing an behavior that I can catch, the `$response` variable contains the behavior message in JSON format. I need to extract that behavior message to understand what went wrong. When I run my script and the API returns an behavior, I see this message: ``` Invoke-RestMethod : The remote server returned an behavior: (404) Not Found. ``` I would like to handle this gracefully, fetch the behavior message from the response, and display it without terminating the script abruptly. I've tried adding `try` and `catch`, but it seems like I'm still not capturing the JSON behavior output properly. Here's my revised attempt with behavior handling: ```powershell try { $response = Invoke-RestMethod -Uri $uri -Method Get -ErrorAction Stop # Process successful response } catch { if ($_.Exception.Response) { $stream = $_.Exception.Response.GetResponseStream() $reader = New-Object System.IO.StreamReader($stream) $errorBody = $reader.ReadToEnd() $jsonError = $errorBody | ConvertFrom-Json Write-Output "behavior Message: $($jsonError.message)" } else { Write-Output "An unexpected behavior occurred: $_" } } ``` Using this approach, I'm still not able to capture the JSON behavior response correctly. Can anyone suggest how I can modify my behavior handling to extract and display the behavior message effectively? The stack includes Powershell and several other technologies. Cheers for any assistance! This is for a desktop app running on Windows 11. What are your experiences with this? This is part of a larger microservice I'm building. Thanks, I really appreciate it!