gpt4 book ai didi

powershell - 使用嵌套原始错误在 powershell 中引发异常

转载 作者:行者123 更新时间:2023-12-03 13:20:31 25 4
gpt4 key购买 nike

我是一名 C# 开发人员,正在尝试使用 PowerShell 构建一些有用的东西。这就是为什么我一直尝试在 PowerShell 中使用 .NET 世界中众所周知的习语。

我正在编写一个具有不同抽象层的脚本:数据库操作、文件操作等。在某些时候,我想捕获一个错误并将其包装成对最终用户更有意义的东西。这是 C#/Java/C++ 代码的常见模式:

Function LowLevelFunction($arg)
{
# Doing something very useful here!
# but this operation could throw
if (!$arg) {throw "Ooops! Can't do this!"}
}

现在,我想调用这个函数并包装一个错误:
Function HighLevelFunction
{
Try
{
LowLevelFunction
}
Catch
{
throw "HighLevelFunction failed with an error!`nPlease check inner exception for more details!`n$_"
}
}

这种方法几乎是我需要的,因为 HighLevelFunction将抛出新错误,原始错误的根本原因将丢失!

在 C# 代码中,我总是可以抛出新异常并提供原始异常作为内部异常。在这种情况下 HighLevelFunction将能够以对客户更有意义的形式传达他们的错误,但仍会提供用于诊断目的的内部细节。

在 PowerShell 中打印原始异常的唯一方法是使用 $Error存储所有异常的变量。这没关系,但是我的脚本的用户(现在是我自己)应该做更多我想做的事情。

所以问题是: 有没有办法在 PowerShell 中引发异常并将原始错误作为内部错误提供?

最佳答案

你可以在你的 catch 中抛出一个新的异常阻止并指定基本异常:

# Function that will throw a System.IO.FileNotFoundExceptiopn
function Fail-Read {
[System.IO.File]::ReadAllLines( 'C:\nonexistant' )
}

# Try to run the function
try {
Fail-Read
} catch {
# Throw a new exception, specifying the inner exception
throw ( New-Object System.Exception( "New Exception", $_.Exception ) )
}

# Check the exception here, using getBaseException()
$error[0].Exception.getBaseException().GetType().ToString()

关于powershell - 使用嵌套原始错误在 powershell 中引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30626153/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com