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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With