簡體   English   中英

Powershell 不捕獲來自 NewWebServiceProxy 的異常

[英]Powershell don't catch exception from NewWebServiceProxy

我在從 NewWebServiceProxy cmdlet 捕獲異常時遇到問題

try {
    $myService = New-WebServiceProxy -Uri "http://localhost/someservice.svc"
}
catch {
    Write-Log ([string]::Format("Error : {0}", $_.Exception.Message))
}

當我運行它時,我得到這個未處理的異常:New-WebServiceProxy:

請求失敗,狀態為 HTTP 404:未找到。 在 C:\Users\SomeUser\AppData\Local\Temp\d052b604-38ad-4827-b952-4ebc66e79c69.ps1:2 char:18 + $myService = New-WebServiceProxy -Uri "http://localhost/someservice.svc" + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~ + CategoryInfo: ObjectNotFound: ( http://localhost/someservice.svc:Uri ) [New-WebServiceProxy], WebExc eption + FullyQualifiedErrorId: WebException,Microsoft.PowerShell.Commands.NewWebServiceProxy

有人會問我為什么 try catch 不捕獲這個異常? 感謝您的回答

這是在PowerShell中捕獲未處理的異常時最常見的問題之一。 您需要在命令New-WebServiceProxy使用-ErrorAction Stop

try {
    $myService = New-WebServiceProxy -Uri "http://localhost/someservice.svc" -ErrorAction Stop
}
catch [System.Net.WebException]{
    Write-Log ([string]::Format("Error : {0}", $_.Exception.Message))
}

更新:要捕獲Http異常包括[System.Net.WebException]Keith Hill在下面的評論中所述。

對我有幫助的是做一些更像是

try{
    New-WebServiceProxy -URI $webURL -ErrorAction Stop
}
catch [System.Net.WebException] {
        return [PSCustomObject]@{
            SOAPStatus = 'Failed'
            SOAPException = $_.Exception.Message
            SOAPInnerException = $_.Exception.InnerException.Message
        } 
    }
    catch {
        return [PSCustomObject]@{
            SOAPStatus = 'Failed'
            SOAPError = $_.Exception.Message
        } 
    }

通過捕獲內部異常,我發現如果有問題,我也會得到 web 響應。 在這些情況下,output 通常是這樣的:

SOAPStatus:SOAPException 失敗:下載“http://webserviceurl.com:1010/SystemServiceQuery”時出錯。

SOAPInnerException:請求失敗,狀態為 HTTP 401:未經授權。

當然,您隨后可以捕獲什么類型的 innerexception 並向您的用戶等提供更有用的反饋。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM