Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell don't catch exception from NewWebServiceProxy

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

like image 515
Zabaa Avatar asked Mar 22 '23 13:03

Zabaa


1 Answers

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.

like image 92
Mitul Avatar answered Apr 06 '23 12:04

Mitul