Powershell 抛出数据异常
Powershell throw exceptions with data
如何在 PowerShell 中使用 'throw' 指令来抛出自定义数据对象的异常?
说,它能做到吗?:
throw 'foo', $myData
那么数据可以用在'catch'逻辑中:
catch {
if ($_.exception.some_property -eq 'foo') {
$data = $_.exception.some_field_to_get_data
# dealing with data
}
}
已编辑:
我的目的是知道是否有一个简短而酷的语法来抛出一个异常(没有明确创建我自己的类型),我可以通过它的名字来决定它的名字并在 'catch' 块中处理它的数据。
您可以 throw
任何类型的 System.Exception
实例(此处以 XamlException
为例):
try {
$Exception = New-Object System.Xaml.XamlException -ArgumentList ("Bad XAML!", $null, 10, 2)
throw $Exception
}
catch{
if($_.Exception.LineNumber -eq 10){
Write-Host "Error on line 10, position $($_.Exception.LinePosition)"
}
}
如果您使用的是 运行 PowerShell 5.0 或更高版本,则可以使用新的 PowerShell 类 功能来定义自定义异常类型:
class MyException : System.Exception
{
[string]$AnotherMessage
[int]$SomeNumber
MyException($Message,$AnotherMessage,$SomeNumber) : base($Message){
$this.AnotherMessage = $AnotherMessage
$this.SomeNumber = $SomeNumber
}
}
try{
throw [MyException]::new('Fail!','Something terrible happened',135)
}
catch [MyException] {
$e = $_.Exception
if($e.AnotherMessage -eq 'Something terrible happened'){
Write-Warning "$($e.SomeNumber) terrible things happened"
}
}
如何在 PowerShell 中使用 'throw' 指令来抛出自定义数据对象的异常? 说,它能做到吗?:
throw 'foo', $myData
那么数据可以用在'catch'逻辑中:
catch {
if ($_.exception.some_property -eq 'foo') {
$data = $_.exception.some_field_to_get_data
# dealing with data
}
}
已编辑:
我的目的是知道是否有一个简短而酷的语法来抛出一个异常(没有明确创建我自己的类型),我可以通过它的名字来决定它的名字并在 'catch' 块中处理它的数据。
您可以 throw
任何类型的 System.Exception
实例(此处以 XamlException
为例):
try {
$Exception = New-Object System.Xaml.XamlException -ArgumentList ("Bad XAML!", $null, 10, 2)
throw $Exception
}
catch{
if($_.Exception.LineNumber -eq 10){
Write-Host "Error on line 10, position $($_.Exception.LinePosition)"
}
}
如果您使用的是 运行 PowerShell 5.0 或更高版本,则可以使用新的 PowerShell 类 功能来定义自定义异常类型:
class MyException : System.Exception
{
[string]$AnotherMessage
[int]$SomeNumber
MyException($Message,$AnotherMessage,$SomeNumber) : base($Message){
$this.AnotherMessage = $AnotherMessage
$this.SomeNumber = $SomeNumber
}
}
try{
throw [MyException]::new('Fail!','Something terrible happened',135)
}
catch [MyException] {
$e = $_.Exception
if($e.AnotherMessage -eq 'Something terrible happened'){
Write-Warning "$($e.SomeNumber) terrible things happened"
}
}