internal/functions/core/Clear-EntraErrorEntry.ps1

function Clear-EntraErrorEntry {
    <#
    .SYNOPSIS
        Removes a caught error of a web call from $Error.

    .DESCRIPTION
        PowerShell adds an error to $Error even when a catch block handles it. The record of a failed web call holds
        the answer's body and the request with its token, so it is removed: every entry that is the record, or whose
        exception is the record's exception (a rethrow adds the same exception again). A record this module built
        (its exception marked by [PSMicrosoftEntraID.Security.ErrorSanitizer]) is left, it carries no foreign text.
        Used by ConvertTo-EntraSafeErrorRecord, and by Invoke-EntraRetry for each failed attempt it repeats.

    .PARAMETER ErrorRecord
        The record caught in the catch block.

    .EXAMPLE
        PS C:\> Clear-EntraErrorEntry -ErrorRecord $_

        Removes the caught record from $Error.
    #>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [System.Management.Automation.ErrorRecord]
        $ErrorRecord
    )

    if ([PSMicrosoftEntraID.Security.ErrorSanitizer]::IsSafe($ErrorRecord.Exception)) { return }
    $errorList = $global:Error
    if ($null -eq $errorList) { return }
    $originalException = $ErrorRecord.Exception
    foreach ($entry in @($errorList.ToArray())) {
        $entryException = if ($entry -is [System.Management.Automation.ErrorRecord]) { $entry.Exception } else { $entry }
        if ([object]::ReferenceEquals($entry, $ErrorRecord) -or [object]::ReferenceEquals($entryException, $originalException)) {
            $errorList.Remove($entry)
        }
    }
}