Capture reason for failure of 'Test-Json' when using a try/catch block

Viewed 192

In PowerShell I am validating some JSON against a schema using the Test-Json cmdlet. When the JSON is invalid against the schema, details are printed on the screen. However, if the Test-Json command is wrapped in a try/catch block those details are lost.

For example...

Test-Json -Json $json -Schema $schema

if this test fails but there is no try/catch block you could expect to see something similar to this (taken from the documentation) -

Test-Json : IntegerExpected: #/age
At line:1 char:37
+ "{'name': 'Ashley', 'age': '25'}" | Test-Json -Schema $schema
+                                     ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidData: (:) [Test-Json], Exception
+ FullyQualifiedErrorId : InvalidJsonAgainstSchema,Microsoft.PowerShell.Commands.TestJsonCommand
False

However, add a try/catch block and now I'm unable to get the actual underlying reason for the failure - IntegerExpected: #/age.

try
{
    Test-Json -Json $json -Schema $schema
}
catch
{
    throw $_.Exception.Message
}

The JSON is not valid with the schema.

In this case there is no inner exception - $_.Exception.InnerException.Message. And there is no additional data with the exception - $_.Exception.Data

Is it possible to retrieve the details of the test failure when catching an error?

0 Answers
Related