New-PSUApiResponse strange responses in a try/catch

New-PSUApiResponse strange responses in a try/catch

avatar

I have some issues with the New-PSUApiResponse. I have done many tests for debugging and my conclusion is:
When an error comes from a function in a try{} block then the catch{} block will do something strange with New-PSUApiResponse. Then it is always Error 400 Badrequest without any output.

For example:

This is an error from ConvertFrom-Json for example with a wrong body format. Where Left is my code and right the result.
$body = '{"sizeGb"= 200}' # Wrong JSON format to test error

This is an error in try{} block itself for example. Where left is also my code and right the result.

I expect that the second example always works with any error from any function.

I hope this is clear enough

907210d1-b2aa-4a3a-a4b9-f6b1bdce01be.png

c3bb20b6-48d8-43e7-a1ea-7f65a4249ec5.png

All Comments (1)

avatar

Hi Romano,

Thank you for the clear examples and screenshots.

We ran your code on PowerShell Universal 2026.3.3 in our lab, endpoint at default settings, with your malformed body {"sizeGb"= 200}. The caught ConvertFrom-Json error returned your own 400 response:

{
"Error": "Failed to parse JSON body",
"Message": "Conversion from JSON failed with error: Invalid character after parsing property name. Expected ':' but got: =. Path '', line 1, position 9."
}

A caught Get-Item error and a throw inside try{} came back the same way, as did your divide-by-zero example. So in our lab, New-PSUApiResponse in the catch{} block works for errors from cmdlets too. In your ConvertFrom-Json screenshot the response has Content-Type application/json and RawContentLength 0, which none of our tests produced, so your setup differs from ours somewhere.

To find what it is, could you send us:
1. Your PowerShell Universal version, operating system, installation type (Windows service, IIS or Docker) and the environment your APIs run in (PowerShell 7 or Windows PowerShell 5.1).
2. The complete endpoint: its New-PSUEndpoint line with all parameters (such as -Environment or -ErrorAction) and the whole script block, or the .ps1 file it points to with -Path.
3. The command you use to call the endpoint, including any content type or headers.

Side note, once you have collected these: New-PSUApiResponse answered text/plain in our tests because the call sets no content type; add -ContentType 'application/json' to return your payload as JSON: https://docs.devolutions.net/powershell-universal/cmdlets/New-PSUApiResponse/

Best regards,

Michel

Michel Audi