英文:
Having issue returning full error information
问题
我正在捕获异常并希望返回完整的内容,并进行了一些测试,它起初是有效的,但现在不起作用,我无法弄清楚是为什么或是否是偶发的。
Try {
Get-Secret -Vault $vaultName -Name $secretId -AsPlainText -EA Stop
}
Catch [System.Management.Automation.ItemNotFoundException] {
# 下一行输出错误消息字符串,如预期
Write-Output ("error:" + $_)
# 仅输出标准错误消息块,但在初始测试期间有效
Write-Error $_ | ConvertTo-Json -Depth 5
# 下一行与前一行类似
# Write-Error $_.Exception | ConvertTo-Json -Depth 5
}
我在这里漏掉了什么?
英文:
I am catching exceptions and want to return the full content and did some tests and it worked but now it isn't working and can't figure out why or if it's intermittent.
Try {
Get-Secret -Vault $vaultName -Name $secretId -AsPlainText -EA Stop
}
Catch [System.Management.Automation.ItemNotFoundException] {
# Next line outputs the error message string, as expected
Write-Output ("error:" + $_)
# Only outputs standard error message block, but worked during initial testing
Write-Error $_ | ConvertTo-Json -Depth 5
#Next line just like previous
#Write-Error $_.Exception | ConvertTo-Json -Depth 5
}
What am I missing here?
答案1
得分: 1
您将捕获的错误 ($_
) 发送到错误流时,使用 Write-Error
和 ConvertTo-Json
只能捕获发送到成功流的输出。
如果您想序列化错误记录并 不将其发送到错误流,只需移除 Write-Error
:
Try {
throw 'foo'
}
Catch {
$_ | ConvertTo-Json -Depth 5
}
如果您想序列化错误记录 并将其发送到错误流,那么 Write-Error
应该是管道中的最后一项:
Try {
throw 'foo'
}
Catch {
$_ | ConvertTo-Json -Depth 5 | Write-Error
}
英文:
<!-- language-all: sh -->
You're sending the caught error ($_
) to the Error Stream when using Write-Error
and ConvertTo-Json
can only capture output sent to the Success Stream.
You have 2 options, if you want to serialize the error record and not send it to the Error Stream just remove Write-Error
:
Try {
throw 'foo'
}
Catch {
$_ | ConvertTo-Json -Depth 5
}
If you want to serialize the error record and send it to the Error Stream, then Write-Error
should be the last in your pipeline:
Try {
throw 'foo'
}
Catch {
$_ | ConvertTo-Json -Depth 5 | Write-Error
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论