Powershell don't catch exception from NewWebServiceProxy

5.2k views Asked by At

I have a problem with catching exception from NewWebServiceProxy cmdlet

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

When I run it i get this unhandled exception : New-WebServiceProxy :

The request failed with HTTP status 404: Not Found. At 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

Somebody could ask me why try catch do not catch this exception ? Thanks for any aswer

2

There are 2 answers

5
Mitul On

This is one of the most common issues while catching an unhandled exception in powershell. You need to use -ErrorAction Stop in the command New-WebServiceProxy

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

Updated: To catch Http exception include [System.Net.WebException] as noted by Keith Hill in the comment below.

0
Ron Zimmer On

What helped me was doing something more like

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
        } 
    }

By catching the inner exception I found I would get the web response as well if there was an issue with it. Which usually in these cases there was something like this for output:

SOAPStatus : Failed SOAPException : There was an error downloading 'http://webserviceurl.com:1010/SystemServiceQuery'.

SOAPInnerException : The request failed with HTTP status 401: Unauthorized.

Of course you could then capture what type of innerexception and give more useful feedback to your users and such.