遇到问题返回完整的错误信息。

huangapple go评论79阅读模式
英文:

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-ErrorConvertTo-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 &#39;foo&#39;
}
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 &#39;foo&#39;
}
Catch {
    $_ | ConvertTo-Json -Depth 5 | Write-Error
}

huangapple
  • 本文由 发表于 2023年2月26日 23:56:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/75573192.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定