Skip to content

Preserve original exception types in ErrorRecord instead of converting to string #180

@coderabbitai

Description

@coderabbitai

Problem

Several New-*Exception functions in the codebase are converting exception objects to strings when creating ErrorRecord objects, which loses the original exception type information.

Current Behavior

The exception functions use patterns like:

$errorSplat = @{
    Exception     = $exception.ToString()  # ❌ Converts to string
    ErrorId       = 'SomeErrorId'
    ErrorCategory = [System.Management.Automation.ErrorCategory]::SomeCategory
}

Expected Behavior

The exception object should be preserved:

$errorSplat = @{
    Exception     = $exception  # ✅ Preserves exception type
    ErrorId       = 'SomeErrorId'
    ErrorCategory = [System.Management.Automation.ErrorCategory]::SomeCategory
}

Impact

When exceptions are converted to strings, the ErrorRecord.Exception property loses the original exception type (e.g., System.InvalidOperationException becomes a string), making it harder for callers to handle specific exception types programmatically.

Files Affected

Based on the current PR #179, this pattern appears in:

  • source/Public/New-InvalidOperationException.ps1 (line 76)
  • source/Public/New-InvalidResultException.ps1 (line 59)
  • source/Public/New-ObjectNotFoundException.ps1 (line 53)
  • source/Public/New-NotImplementedException.ps1 (line 74)

Note: New-InvalidDataException.ps1 already correctly uses the exception object directly.

References

Acceptance Criteria

  • All New-*Exception functions preserve the original exception type in ErrorRecord
  • Unit tests verify that ErrorRecord.Exception maintains the correct exception type
  • Existing functionality and error behavior are preserved
  • All tests pass

/cc @dan-hughes

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions