Private/Resolve-SIAError.ps1

function Resolve-SIAError {
    <#
    Turns a failed Invoke-RestMethod call into a readable, non-terminating-safe
    error message: HTTP status, the operation and endpoint that failed, and
    whatever message CyberArk returned in the response body. CyberArk does not
    document a fixed correlation-id header name, so a few common candidates
    are checked on a best-effort basis rather than assumed.
    #>

    [CmdletBinding()]
    [OutputType([string])]
    param(
        [Parameter(Mandatory)]
        [System.Management.Automation.ErrorRecord]$ErrorRecord,

        [Parameter(Mandatory)]
        [string]$Operation,

        [Parameter(Mandatory)]
        [uri]$Uri
    )

    $statusCode = $null
    $requestId = $null
    $response = $ErrorRecord.Exception.Response

    if ($response) {
        $statusCode = [int]$response.StatusCode

        if ($response.Headers) {
            foreach ($headerName in 'x-correlation-id', 'x-request-id', 'correlationid') {
                $values = $null
                if ($response.Headers.TryGetValues($headerName, [ref]$values)) {
                    $requestId = ($values | Select-Object -First 1)
                    break
                }
            }
        }
    }

    $cyberArkMessage = $null
    $rawBody = $ErrorRecord.ErrorDetails.Message
    if ($rawBody) {
        try {
            $parsed = $rawBody | ConvertFrom-Json -ErrorAction Stop
            $cyberArkMessage = @($parsed.message, $parsed.error_description, $parsed.error, $parsed.Details) |
                Where-Object { $_ } | Select-Object -First 1
        } catch {
            $cyberArkMessage = $rawBody
        }
    }

    $lines = [System.Collections.Generic.List[string]]::new()
    $lines.Add("SIA request failed with HTTP $statusCode.")
    $lines.Add("Operation: $Operation")
    $lines.Add("Endpoint: $Uri")
    if ($cyberArkMessage) {
        $lines.Add("Message: $(Protect-SIALogValue -InputObject ([string]$cyberArkMessage))")
    }
    if ($requestId) {
        $lines.Add("Request ID: $requestId")
    }

    $lines -join "`n"
}