使用类时处理异常

时间:2017-11-09 14:15:18

标签: class powershell error-handling exception-handling powershell-v5.0

有哪些选项可用于处理类方法中的异常?

即。使用高级功能,我们可以做到这一点:

function Test-Error {
    [CmdletBinding()]
    Param()
    throw "Error!" 
}

"1. Error's about to happen"
Test-Error -ErrorAction SilentlyContinue
"1. Error just happenned (you didn't see it)"

"2. Error's about to happen"
Test-Error -ErrorAction Stop
"2. Error just happened (you saw it; but you won't see this)"

要在调用类方法时获得相同的行为,我可以这样做:

class ErrorTest
{
    ErrorTest(){}
    TestError(){ throw "Error!" }
}
[ErrorTest]$e = [ErrorTest]::new()


"1. Error's about to happen"
$ErrorActionPreference = 'SilentlyContinue'
$e.TestError() 
"1. Error just happened (you didn't see it)"

"2. Error's about to happen"
$ErrorActionPreference = 'Stop'
$e.TestError() 
"2. Error just happened (you saw it; but you won't see this)"

但我不喜欢改变ErrorActionPreference。是否有更好的解决方案/处理此类方案的标准方法?

更新

根据TheIncorrigible1的评论,也尝试使用这种抛出异常的方法:

function Test-Error {
    [CmdletBinding()]
    Param()
    $badObject = 'whatever object caused the issue'
    $actualException = [System.NotSupportedException]::new('I take exception to your use of this function')
    $errorRecord = [System.Management.Automation.ErrorRecord]::new($actualException, 'ExampleException1', [System.Management.Automation.ErrorCategory]::InvalidData, $badObject)
    $PSCmdlet.ThrowTerminatingError($errorRecord) 
}

0 个答案:

没有答案