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)" }
    if ($ErrorRecord.Exception.Response) {
        try {
            $stream = $ErrorRecord.Exception.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
}