Common/Error/Error.psm1

Import-Module -Name $PSScriptRoot\..\Wrappers\Wrappers

function Show-RMError {
    param(
        [Parameter(Mandatory)]
        [System.Management.Automation.ErrorRecord] $ErrorObj
    )
    $ErrorString = $ErrorObj.ToString()
    if($ErrorString.Contains("validation_errors")) {
        $ErrorString = $ErrorString | ConvertFrom-Json
        foreach($Message in $ErrorString.validation_errors.errors) {
            if ($null -eq $Message.message) {
                Write-RMError -Message $ErrorObj.ToString()
                break
            } else {
                Write-RMError -Message $Message.message
            }
        }
    } elseif ($ErrorString.Contains("message") -And $ErrorString.Contains("resolution")) {
        $ErrorStringJson = $ErrorString | ConvertFrom-Json
        if ($null -ne $ErrorStringJson.message -and $null -ne $ErrorStringJson.resolution) {
            Write-RMError -Message $ErrorStringJson.message
            Write-RMError -Message $ErrorStringJson.resolution
        } elseif ($null -ne $ErrorStringJson.message) {
            if ($ErrorStringJson.message -eq "Authentication is required to view resource.") {
                throw "Authentication credentials have expired, please re-login using cmdlet 'Invoke-RMLogin'"
            }
            Write-RMError -Message  $ErrorStringJson.message
        } else {
            Write-RMError -Message  $ErrorObj.ToString()
        }
    } else {
        Write-RMError -Message $ErrorString
    }
}

Export-ModuleMember -Function Show-RMError