【问题标题】:Powershell don't catch exception from NewWebServiceProxyPowershell 不会从 NewWebServiceProxy 捕获异常
【发布时间】:2013-09-06 19:15:20
【问题描述】:

我在从 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 字符:18 + $myService = New-WebServiceProxy -Uri "http://localhost/someservice.svc" + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (http://localhost/someservice.svc:Uri) [New-WebServiceProxy], WebExc 选项 + FullyQualifiedErrorId : WebException,Microsoft.PowerShell.Commands.NewWebServiceProxy

有人可能会问我为什么 try catch 不捕获这个异常?感谢您的任何回答

【问题讨论】:

    标签: web-services exception powershell exception-handling new-webserviceproxy


    【解决方案1】:

    这是在 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))
    }
    

    更新:如 Keith Hill 在下面的评论中指出,要捕获 Http 异常包括 [System.Net.WebException]。

    【讨论】:

    • 感谢它的工作,但我现在捕获的异常与上面的异常不同(HTTP 状态 404)。实际捕获的异常:There was an error downloading 'http://localhost/someservice.svc'。我能捕捉到 404 异常吗?
    • 我想你想捕捉 [System.Net.WebException]。
    • 是的,但即使我添加 catch [System.Net.WebException] ps 也不会收到。
    • 我尝试调用请求try { $request = [System.Net.WebRequest]::Create("http://localhost/someservice.svc") $response = $request.GetResponse() } catch { Write-Error ([string]::Format("Response from request : {0}", $_.Exception.Message)) } 并抓住给我这个:Exception c alling "GetResponse" with "0" argument(s): "The remote server returned an error: (404) Not Found."
    • 因此,如果您正在执行 System.Net.WebRequest,那么您需要在捕获 404 时检查这一点。stackoverflow.com/questions/9090849/…
    猜你喜欢
    • 2013-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-14
    • 2018-01-14
    • 1970-01-01
    相关资源
    最近更新 更多