Private/ConvertTo-FloRecruitError.ps1

function ConvertTo-FloRecruitError {
    <#
    .SYNOPSIS
        Converts HTTP error responses to standardized PowerShell ErrorRecord objects.

    .DESCRIPTION
        Parses error responses from the FloRecruit API and creates properly categorized
        ErrorRecord objects with helpful error messages.

    .PARAMETER Exception
        The exception object from the web request.

    .PARAMETER ErrorDetails
        The error details string from the response.

    .PARAMETER StatusCode
        The HTTP status code from the response.
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [System.Exception]$Exception,

        [Parameter()]
        [string]$ErrorDetails,

        [Parameter()]
        [int]$StatusCode
    )

    # Define status code to error category mapping
    $categoryMap = @{
        400 = [System.Management.Automation.ErrorCategory]::InvalidArgument
        401 = [System.Management.Automation.ErrorCategory]::AuthenticationError
        403 = [System.Management.Automation.ErrorCategory]::PermissionDenied
        404 = [System.Management.Automation.ErrorCategory]::ObjectNotFound
        429 = [System.Management.Automation.ErrorCategory]::LimitsExceeded
        500 = [System.Management.Automation.ErrorCategory]::NotSpecified
        502 = [System.Management.Automation.ErrorCategory]::ConnectionError
        503 = [System.Management.Automation.ErrorCategory]::ResourceUnavailable
        504 = [System.Management.Automation.ErrorCategory]::OperationTimeout
    }

    # Get the appropriate error category
    $errorCategory = $categoryMap[$StatusCode]
    if (-not $errorCategory) {
        $errorCategory = [System.Management.Automation.ErrorCategory]::NotSpecified
    }

    # Try to parse error message from response
    $errorMessage = $Exception.Message
    if ($ErrorDetails) {
        try {
            $errorObject = $ErrorDetails | ConvertFrom-Json -ErrorAction SilentlyContinue
            if ($errorObject.message) {
                $errorMessage = $errorObject.message
            }
            elseif ($errorObject.error) {
                $errorMessage = $errorObject.error
            }
            elseif ($errorObject.error_description) {
                $errorMessage = $errorObject.error_description
            }
        }
        catch {
            # If JSON parsing fails, use the raw error details
            $errorMessage = $ErrorDetails
        }
    }

    # Create formatted error message
    $formattedMessage = "FloRecruit API Error (HTTP $StatusCode): $errorMessage"

    # Create and return ErrorRecord
    $errorRecord = New-Object System.Management.Automation.ErrorRecord(
        (New-Object Exception $formattedMessage),
        "FloRecruitApiError$StatusCode",
        $errorCategory,
        $null
    )

    return $errorRecord
}