Powershell does not exclude exceptions 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:

Request error with HTTP status 404: not found. In 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

Can anyone ask me why try catch does not catch this exception? Thank you for any user.

+4
source share
1 answer

This is one of the most common problems when you encounter an unhandled exception in powershell. You must use -ErrorAction Stop in the New-WebServiceProxy command

 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 the Http exception, enable [System.Net.WebException] as pointed out by Keith Hill in the comment below.

+6
source

Source: https://habr.com/ru/post/1500313/


All Articles