使用默认消息扩展 Powershell 中的异常



我一直在尝试扩展PowerShell中的异常。我在课堂上的第一遍是这样的...

class CustomException : Exception {
CustomException () {
}
CustomException ([String] $message) : base ($message) {
}
}

并且使用是预期的,这里的第一种方法生成类型名称,第二种方法生成提供的消息......

try {
throw [CustomException]
} catch {
"$($_.Exception.Message)"
}
try {
throw [CustomException] 'Another message'
} catch {
"$($_.Exception.Message)"
}

但是,我真的很想有一个默认消息,所以我可以在很多地方使用第一个示例,但是如果我想修改消息,我可以在课堂上做一次。或者甚至可以在某个时候本地化消息。这个线程似乎表明它在 C# 中是可能的,尤其是最后两篇文章。所以,以最后一个例子为例...

public class MyException : Exception
{
public MyException () : base("This is my Custom Exception Message")
{
}
}

我以为我可以在Powershell中做同样的事情,就像这样......

CustomException () : base ('Default message') {
}

但是当我不提供消息时,我仍然会得到类型名称。这引起了我的思考,我尝试了...

try {
throw [System.IO.FileNotFoundException]
} catch {
"$($_.Exception.Message)"
}

而且这也不提供默认消息,只提供类名。那么,C#代码没有做我认为它正在做的事情吗?或者这只是Powershell中行为的差异?还是我做错了什么?

你想要的完全支持,但你需要抛出一个异常的实例

throw的语法基本上是:

throw [Throwable]

其中Throwable是错误记录、异常或字符串(基本上是裸错误消息(。

当你抛出类型文字[CustomException]时,PowerShell将该表达式转换为[string],这就是为什么你只在catch块中看到类型名称。

正确引发异常实例需要调用构造函数:

class CustomException : Exception
{
CustomException() : base("default CustomException message goes here")
{
}
}
try {
throw [CustomException]::new()    # <-- don't forget to call the constructor
} catch {
"$_"
}

最新更新