Private/ConvertTo-GhostErrorRecord.ps1

function ConvertTo-GhostErrorRecord {
    <#
    .SYNOPSIS
        Turns a failed web request into an error that shows what Ghost reported.

    .DESCRIPTION
        Ghost answers a failed request with a JSON document such as
        {"errors":[{"message":"...","context":"...","type":"NotFoundError"}]}. The web cmdlets only show the HTTP
        status, so the message, the context and the type are taken from that document.

        The error id of the returned record is the Ghost error type, for example NotFoundError or
        UpdateCollisionError. The HTTP status code and the parsed error are available in the Data property of
        the exception, under StatusCode and GhostError.

    .EXAMPLE
        ConvertTo-GhostErrorRecord -ErrorRecord $_ -Method 'Get' -Uri $uri

        Inside a catch block, returns an error record with the message Ghost returned for the failed request.
    #>

    [CmdletBinding()]
    [OutputType([System.Management.Automation.ErrorRecord])]
    param(
        # The error that the web request raised.
        [Parameter(Mandatory)]
        [System.Management.Automation.ErrorRecord] $ErrorRecord,

        # The HTTP method of the failed request.
        [Parameter(Mandatory)]
        [string] $Method,

        # The URI of the failed request.
        [Parameter(Mandatory)]
        [string] $Uri
    )

    # Windows PowerShell and PowerShell 7 raise different exception types; both expose the response, when
    # there is one, as a Response property with a StatusCode.
    $statusCode = 0
    $response = $ErrorRecord.Exception.PSObject.Properties['Response']
    if ($response -and $response.Value) {
        $statusCode = [int] $response.Value.StatusCode
    }

    $type = 'GhostApiError'
    $detail = $ErrorRecord.Exception.Message
    $ghostError = $null

    if ($ErrorRecord.ErrorDetails -and $ErrorRecord.ErrorDetails.Message) {
        $document = $null
        try {
            $document = ConvertFrom-Json -InputObject $ErrorRecord.ErrorDetails.Message
        }
        catch {
            # Not every failure comes from Ghost itself; a proxy in front of it answers with HTML, for example.
            Write-Debug -Message "The error response is not JSON: $($_.Exception.Message)"
        }

        $errors = $null
        if ($document -is [System.Management.Automation.PSCustomObject]) {
            $errors = $document.PSObject.Properties['errors']
        }
        if ($errors -and $errors.Value) {
            $ghostError = @($errors.Value)[0]

            # Read the fields by name: which ones are present differs between Ghost versions.
            $field = @{}
            foreach ($name in 'message', 'context', 'type', 'errorType') {
                $property = $ghostError.PSObject.Properties[$name]
                $field[$name] = if ($property) { $property.Value }
            }

            $text = @($field['message'], $field['context']) | Where-Object { $_ }
            if ($text) {
                $detail = $text -join ' '
            }
            $reportedType = @($field['type'], $field['errorType']) | Where-Object { $_ } | Select-Object -First 1
            if ($reportedType) {
                $type = [string] $reportedType
            }
        }
    }

    $category = switch ($statusCode) {
        0 { [System.Management.Automation.ErrorCategory]::ConnectionError }
        401 { [System.Management.Automation.ErrorCategory]::AuthenticationError }
        403 { [System.Management.Automation.ErrorCategory]::PermissionDenied }
        404 { [System.Management.Automation.ErrorCategory]::ObjectNotFound }
        409 { [System.Management.Automation.ErrorCategory]::ResourceExists }
        422 { [System.Management.Automation.ErrorCategory]::InvalidData }
        default { [System.Management.Automation.ErrorCategory]::InvalidOperation }
    }

    $status = if ($statusCode) { "HTTP $statusCode $type" } else { 'no response' }
    $message = 'Ghost API request failed ({0}): {1} [{2} {3}]' -f $status, $detail, $Method.ToUpperInvariant(), $Uri

    $exception = [System.InvalidOperationException]::new($message, $ErrorRecord.Exception)
    $exception.Data['StatusCode'] = $statusCode
    $exception.Data['GhostError'] = $ghostError

    [System.Management.Automation.ErrorRecord]::new($exception, $type, $category, $Uri)
}