PowerShell 技能连载 - 高级错误处理:重新抛出异常

在处理错误时,您有时会希望将原始的异常替换成您自己的。以下是一个例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function Do-Something
{
# function uses internal error handling
try
{
Get-Process -Name NotThereOhWell -ErrorAction Stop
}
# catch this error type
catch [Microsoft.PowerShell.Commands.ProcessCommandException]
{
$oldE = $_.Exception

# handle the error, OR SHOWN HERE: issue a new exception to the caller
$newE = New-Object -TypeName System.InvalidOperationException('Do-Something: A fatal error occured', $oldE)
Throw $newE
}
}

# function will encounter an internal error
# error message shows error message generated by function instead
Do-Something

调用者看到的内容如下:

1
2
3
4
5
6
7
PS C:\>  Do-Something
Do-Something: A fatal error occured
At line:18 char:5
+ Throw $newException
+ ~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], InvalidOperationException
+ FullyQualifiedErrorId : Do-Something: A fatal error occured

如果调用者也用一个错误处理函数来接收它,则会出现这种情况:

1
2
3
4
5
6
7
8
9
10
11
try
{
Do-Something
}
catch [System.InvalidOperationException]
{
[PSCustomObject]@{
Message = $_.Exception.Message
Originalmessage = $_.Exception.InnerException.Message
}
}

结果看起来如下:

1
2
3
4
5
Message                             Originalmessage
------- ---------------
Do-Something: A fatal error occured Cannot find a process with the name
"NotThereOhWell". Verify the process name
and call the cmdlet again.

这样调用者可以看到返回的错误信息,并且经过内部处理之后,还可以传递原始的错误信息。

PowerShell 技能连载 - 高级错误处理:重新抛出异常

http://blog.vichamp.com/2016/11/29/advanced-error-handling-rethrowing-exceptions/

作者

吴波

发布于

2016-11-29

更新于

2022-07-06

许可协议

评论