【发布时间】:2018-10-30 10:59:22
【问题描述】:
我有一个针对 Windows PowerShell 5.1 运行的现有 PowerShell 模块。它在很大程度上取决于 Invoke-WebRequest 和 Invoke-RestMethod cmdlet,它们在 5.1 和 PowerShell Core 6 之间有一些 fairly significant changes。
我已经设法使大部分代码在不同版本(桌面/核心)之间工作,但我遇到的最后一件事是处理 HTTP 失败响应引发的异常。现有代码看起来或多或少是这样的。
try {
$response = Invoke-WebRequest @myparams -EA Stop
# do more stuff with the response
} catch [System.Net.WebException] {
# parse the JSON response body for error details
}
除了来自服务器的 HTTP 响应代码失败所生成的异常之外,我不一定要捕获任何异常。 Core 版返回的异常类型与桌面版不同,需要单独的代码路径来解析响应。所以最初我尝试了这个:
try {
$response = Invoke-WebRequest @myparams -EA Stop
# do more stuff with the response
} catch [System.Net.WebException] {
# Desktop: parse the JSON response body for error details
} catch [Microsoft.PowerShell.Commands.HttpResponseException] {
# Core: parse the JSON response body for error details
}
在 Core 中运行时可以正常工作。但在 Desktop 中运行时,我收到 Unable to find type [Microsoft.PowerShell.Commands.HttpResponseException] 错误。
解决此问题的最佳方法是什么?我是否需要捕获所有异常,类型上的字符串匹配,然后重新抛出我不想要的?有没有一种更优雅的方式,不涉及为 PowerShell 的桌面版和核心版发布单独的模块版本?
【问题讨论】:
-
我确实会采用文本方式。
catch [Exception],然后打开$_.Exception.GetType().FullName并使用默认的throw操作。这应该可以很好地跨平台工作,并且没有比您的示例更多的代码行。
标签: powershell powershell-core