I am writing a script that heavily utilizes an API. I have a large custom error handling function for the various error responses from Invoke-RestMethod calls that I would like to be able to unit test appropriately.
I saved some of these errors by using Export-CliXml, however I'm not actually able to rebuild the object back to it's original form. At some point when I'm expecting data I just get strings, and when I increase the -Depth parameter for Export-Clixml, Powershell takes a huge amount of time to write a gigantic .xml file.
For example I get an Http Response Error from Invoke-RestMethod, I check the status code and use that for some custom error handling in some of the scenarios. This is grabbed with $ErrorRecord.Exception.Response.StatusCode.Value__
. However when I try to rebuild the CliXml object, everything held in the nested 'Response' object turns into just a string and I can't parse it in the same way.
So my questions are:
Is there a good way to export a complicated, nested, error record object that doesn't take a huge amount of time to export and import?
How is it that powershell gets the response and creates this error record in miliseconds, but my exporting and importing of the same object with it's nested properties takes an enormous amount of time?
Public testing API that will just return a 401 unauthorized error:
try {
$global:response = Invoke-RestMethod -Uri "https://reqres.in/api/login" -Method 'POST'
}
catch {
$global:err = $_
}