internal/functions/core/ConvertTo-EntraSafeErrorRecord.ps1
|
function ConvertTo-EntraSafeErrorRecord { <# .SYNOPSIS Turns the error record of a failed web call into a new one without the answer's body, the request or the answer, and removes the original from $Error. .DESCRIPTION Invoke-RestMethod fails with a record that holds the answer's body (ErrorDetails, and with it the text of the record), and an exception that holds the request with its Authorization header and the answer (Exception.Response). A server may echo the request - its token, client secret or query - in the body, and PowerShell re-escapes a JSON body (\u002B for +), so masking known values is not reliable. The record is replaced, fail closed, by [PSMicrosoftEntraID.Security.ErrorSanitizer]: its message names the HTTP status, the error codes of the body that are identifiers (invalid_client, AADSTS7000215, Authorization_RequestDenied), the request id when it is a GUID and the exception type; the status stays in Exception.StatusCode and Exception.Data['StatusCode'], the codes in Data['ErrorCode'], the request id in Data['RequestId']. There is no inner exception, target object or error details. PowerShell has already added the original record to $Error (a caught error is added too); every entry of that record or its exception is removed there. A record that needs no change is returned as it is. Use it as: catch { $PSCmdlet.ThrowTerminatingError((ConvertTo-EntraSafeErrorRecord -ErrorRecord $_)) } Ported from PSDataFactory (ConvertTo-PSDataFactorySafeErrorRecord). .PARAMETER ErrorRecord The record caught in the catch block. .EXAMPLE PS C:\> try { Invoke-RestMethod @parameters -ErrorAction Stop } catch { $PSCmdlet.ThrowTerminatingError((ConvertTo-EntraSafeErrorRecord -ErrorRecord $_)) } Rethrows a failed request as a new record that names its status, error code and request id only. #> [CmdletBinding()] [OutputType([System.Management.Automation.ErrorRecord])] param ( [Parameter(Mandatory = $true)] [System.Management.Automation.ErrorRecord] $ErrorRecord ) $safeRecord = [PSMicrosoftEntraID.Security.ErrorSanitizer]::Sanitize($ErrorRecord) Clear-EntraErrorEntry -ErrorRecord $ErrorRecord $safeRecord } |