【问题标题】:Powershell throw exceptions with dataPowershell 抛出数据异常
【发布时间】:2017-03-01 10:07:43
【问题描述】:

如何在 PowerShell 中使用“抛出”方向来抛出自定义数据对象的异常? 说吧,能做到吗?:

throw 'foo', $myData

那么数据可以用在'catch'逻辑中:

catch {
    if ($_.exception.some_property -eq 'foo') {
        $data = $_.exception.some_field_to_get_data
        # dealing with data
    }
}

编辑:
我的目的是知道是否有一个简短而酷的语法来抛出一个异常(无需显式创建我自己的类型),我可以通过它的名称来决定它的名称并在“catch”块中处理它的数据。

【问题讨论】:

标签: powershell exception throw


【解决方案1】:

您可以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"
    }
}

【讨论】:

  • ("Bad XAML!", $null, 10, 2) welp,你如何找到如何通过这样的东西?
  • @4c74356b41 查看 MSDN 上的构造函数文档(上面链接),或查看重载定义:[System.Xaml.XamlException]::new(v 5.0+)或[System.Xaml.XamlException].GetConstructors()|%{'new {0}({1})'-f$_.DeclaringType,(($_.GetParameters()|%{'{0} {1}'-f$_.ParameterType.FullName,$_.Name})-join', ')}(旧版本)
  • 不完全是我想要的,但它是我的问题的解决方法。真的很鼓舞人心。谢谢大家!
  • @DaveWu 在 PS 5.0 中添加了扩展 System.Exception 类的示例,在早期版本中,您可以使用 C# 或 VB.NET 编写的外部代码来实现此目的
猜你喜欢
  • 1970-01-01
  • 2014-05-20
  • 1970-01-01
  • 2013-05-24
  • 1970-01-01
  • 2023-04-10
  • 2012-09-10
  • 1970-01-01
  • 2020-11-20
相关资源
最近更新 更多