gpt4 book ai didi

System.Net.WebException 的 Powershell 处理

转载 作者:行者123 更新时间:2023-12-03 11:23:08 31 4
gpt4 key购买 nike

几乎掌握了使用 Powershell Invoke-WebRequest 我现在开始尝试控制异常错误

在第一段代码中,我必须处理从 Web 服务返回的异常。您可以看到 400 代码与消息描述和详细消息一起返回。

Try {
$what = Invoke-WebRequest -Uri $GOODURL -Method Post -Body $RequestBody -ContentType $ContentType
}

catch [System.Net.WebException] {
$Request = $_.Exception
Write-host "Exception caught: $Request"

$crap = ($_.Exception.Response.StatusCode.value__ ).ToString().Trim();
Write-Output $crap;
$crapMessage = ($_.Exception.Message).ToString().Trim();
Write-Output $crapMessage;
$crapdescription = ($_.ErrorDetails.Message).ToString().Trim();
Write-Output $crapdescription;
}

输出返回。好的!
Exception caught: System.Net.WebException: The remote server returned an error: (400) Bad Request.
at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.GetResponse(WebRequest request)
at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.ProcessRecord()
400
The remote server returned an error: (400) Bad Request.
Modus.queueFailed Could not queue message http://schemas.xmlsoap.org/soap/actor/next

这非常酷,但是作为我测试的一部分,我想模拟连接错误,所以我给脚本提供了一个无效的 URI,我在上面的代码中的错误处理立即崩溃了。

具体来说,无效的 URI 落在了“$_.Exception.Response.StatusCode.value__”和“$_.ErrorDetails.Message”上,大概是因为它们不存在于返回的 System.Net.WebException 对象中

所以,我把它们拿出来作为测试,果然它可以像下面预期的那样使用无效的 URL
Try {
$what = Invoke-WebRequest -Uri $BADURL -Method Post -Body $RequestBody -ContentType $ContentType
}

catch [System.Net.WebException] {
$Request = $_.Exception
Write-host "Exception caught: $Request"

$crapMessage = ($_.Exception.Message).ToString().Trim();
Write-Output $crapMessage;
}

我明白了(也很好)
Exception caught: System.Net.WebException: The remote name could not be resolved: 'gateway.zzzzsonicmobile.com'
at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
at System.Net.HttpWebRequest.GetRequestStream()
at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.SetRequestContent(WebRequest request, String content)
at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.ProcessRecord()
at System.Management.Automation.CommandProcessor.ProcessRecord()

The remote name could not be resolved: 'gateway.zzzzsonybile.com'

问题是,第一个示例从异常对象中获取了我想要的所有内容,但不适用于无效的 URL。第二个示例处理无效的 URL(连接错误),但我不知道如何获取 400 StatusCode 和 ErrorDetails.Message

如果可能的话,我真的很想这样做。

有没有办法设置它来处理所有异常处理..?

任何帮助,非常感谢..!

最佳答案

我认为您可能只是看到一个问题,因为您正在尝试执行 .ToString().Trim()这些属性不存在时的方法。我不确定执行这些方法是否会增加很多值(value),因此我很想删除它们。

或者,您可以输入 If围绕它们的块,以便它们仅在有值(value)时才输出:

If ($_.Exception.Response.StatusCode.value__) {
$crap = ($_.Exception.Response.StatusCode.value__ ).ToString().Trim();
Write-Output $crap;
}
If ($_.Exception.Message) {
$crapMessage = ($_.Exception.Message).ToString().Trim();
Write-Output $crapMessage;
}

关于System.Net.WebException 的 Powershell 处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44897230/

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