Modules/businessdev.ALbuild.Marketplace/Private/Get-BcMarketplaceErrorDetail.ps1
|
function Get-BcMarketplaceErrorDetail { <# .SYNOPSIS Extracts the response body from a failed Marketplace REST call, for diagnostics. .DESCRIPTION Invoke-RestMethod surfaces only "(400) Bad Request" in the exception message; the Partner Center / Product Ingestion APIs return a JSON body explaining the actual reason. This retrieves that body across Windows PowerShell 5.1 (WebException response stream) and PowerShell 7+ (body pre-read into ErrorDetails.Message), so the real cause is logged instead of a bare status code. .PARAMETER ErrorRecord The ErrorRecord caught in a catch block ($_). .OUTPUTS System.String - the response body, or $null. #> [CmdletBinding()] [OutputType([string])] param( [Parameter(Mandatory)] [System.Management.Automation.ErrorRecord] $ErrorRecord ) if ($ErrorRecord.ErrorDetails -and $ErrorRecord.ErrorDetails.Message) { return "$($ErrorRecord.ErrorDetails.Message)" } # StrictMode-safe: only WebException/HttpResponseException carry a .Response member. Reading it directly # threw "The property 'Response' cannot be found on this object" for every other exception type - which # replaced the caller's real error with this one. Go through PSObject so an absent member reads as $null. $respProp = $ErrorRecord.Exception.PSObject.Properties['Response'] $response = if ($respProp) { $respProp.Value } else { $null } if ($response) { try { $stream = $response.GetResponseStream() if ($stream) { $reader = New-Object System.IO.StreamReader($stream) try { if ($reader.BaseStream.CanSeek) { $reader.BaseStream.Position = 0 }; $body = $reader.ReadToEnd() } finally { $reader.Close() } if ($body) { return "$body" } } } catch { Write-Verbose "Could not read the error response body: $($_.Exception.Message)" } } return $null } |