Skip to content

Report the real exception type from Should-Throw - #2922

Merged
nohwnd merged 1 commit into
mainfrom
fix-2873-should-throw-type
Jul 24, 2026
Merged

Report the real exception type from Should-Throw#2922
nohwnd merged 1 commit into
mainfrom
fix-2873-should-throw-type

Conversation

@nohwnd

@nohwnd nohwnd commented Jul 23, 2026

Copy link
Copy Markdown
Member

Should-Throw runs the scriptblock with InvokeWithContext, so a terminating error comes back wrapped in a MethodInvocationException. Get-ErrorObject unwrapped it to the inner error record and reported its Exception, which for a parameter binding failure (and a division by zero) is only a ParentContainsErrorRecordException placeholder, not the real exception. So Should-Throw -ExceptionType reported the wrong type, unlike Should -Throw.

Get-ErrorObject now reports the same exception that & { } would surface in $_: the inner exception itself when the record only carries the placeholder, and the record's own exception otherwise. Write-Error -ErrorAction Stop and Get-Item -ErrorAction Stop wrap the original record in an ActionPreferenceStopException, so those keep working.

Added tests in Should-Throw.Tests.ps1, they fail without the fix. Thanks @fflaten for the root-cause analysis in the issue.

Fix #2873

🤖

Should-Throw runs the scriptblock with InvokeWithContext, so a terminating
error comes back wrapped in a MethodInvocationException. Get-ErrorObject
unwrapped it to the inner error record and reported its Exception, which for
a parameter binding failure (and a division by zero) is only a
ParentContainsErrorRecordException placeholder, not the real exception. So
Should-Throw -ExceptionType reported the wrong type, unlike Should -Throw.

Get-ErrorObject now reports the same exception that & { } would surface in
$_: the inner exception itself when the record only carries the placeholder,
and the record's own exception otherwise (Write-Error -ErrorAction Stop and
Get-Item -ErrorAction Stop wrap the original record in an
ActionPreferenceStopException, so those keep working).

Fix #2873

🤖
@nohwnd nohwnd added this to the 6.1.0 milestone Jul 23, 2026
@nohwnd
nohwnd merged commit fd365c0 into main Jul 24, 2026
13 checks passed
@nohwnd
nohwnd deleted the fix-2873-should-throw-type branch July 24, 2026 07:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Should-Throw returns wrong exeption type

1 participant