2

New to PowerShell. I am calling API with Power shell and saving the response in the sample file.

It is working fine. Challenge is what should I do if API is having some challenge (Down etc).. not responding etc. In that case, I do not want to save my file. Now it is saving the file with the error.

Tried a lot of try and catch but not able to find the error codes.

try
{


    $uri = "https://my url"
    $response = Invoke-RestMethod -Uri $uri
    $response.Save("C:\Users\rtf\Desktop\Details\samplet.xml")
    Write-Host "done"

} 
catch 
{

    # Dig into the exception to get the Response details.
    # Note that value__ is not a typo.
    Write-Host "StatusCode:" $_.Exception.Response.StatusCode.value__ 
    Write-Host "StatusDescription:" $_.Exception.Response.StatusDescription
}

Above code is based on this stackoverflow answer.

Moerwald
  • 10,448
  • 9
  • 43
  • 83
Andrew
  • 183
  • 2
  • 14
  • 2
    the `try/catch/finally` structure REQUIRES a terminating error in the `try` section. [*grin*] you likely need to add `-ErrorAction Stop` to your `Invoke-RestMethod` line. – Lee_Dailey Jun 30 '19 at 23:47
  • Thanks. $response.Save is a non terminating error. How I can check if this has some 500 error in it. – Andrew Jun 30 '19 at 23:58
  • you need to use something other than try/catch. [*grin*] that REQUIRES a terminating error. us an IF test to check for _errors in the returned info_. – Lee_Dailey Jul 01 '19 at 00:47
  • `not able to find the error codes.` Then you should title your question as such. – Gaurav Singh Jul 01 '19 at 03:03
  • If it helps: see [this answer](https://stackoverflow.com/questions/54779910/if-else-based-on-output-of-invoke-webrequest-in-ps/54782976#54782976) to capture status codes. – Theo Jul 01 '19 at 10:26

1 Answers1

0

As stated in above comment you've to define the ErrorPreference of the Invoke-RestMethod cmdlet. This can be either done by the -ErrorAction parameter (and setting its value to Stop), or via the $ErrorPreference "global" variable.

From devblog:

In reality, this means that if an error occurs and Windows PowerShell can recover from it, it will attempt to execute the next command. But it will let you know the error occurred by displaying the error to the console.

So for non-terminating errors you've to define if PowerShell shall stop execution or simply continue the execution.

Below code sets the ErrorAction to Stop so a non-terminating error will be caught. When will PowerShell detect a terminating error, or what is a terminating error? For example, if you run out of memory, or if PowerShell detects a syntax error.

Since the Invoke-RestMethod docu states:

Windows PowerShell formats the response based to the data type. For an RSS or ATOM feed, Windows PowerShell returns the Item or Entry XML nodes. For JavaScript Object Notation (JSON) or XML, Windows PowerShell converts (or deserializes) the content into objects.

$response may either contain XML or JSON (or something else specific) that PowerShell tries to parse.

Update1: Based on below comment stating an error message, $response contains XML, that PowerShell converts. At the end $response should have a Error status property in case of an error. With the help of Get-Member we can check if $response contains an error property and perform additional error handling.

try
{
     $uri = "https://my url"
     $response = Invoke-RestMethod -Uri $uri -ErrorAction Stop
     # Was a valid response object returned? 
     if ($null -ne $response) {

        # Has the object an REST-API specific Error status property?
        if(Get-Member -inputobject $response-name "UnknownResult" -Membertype Properties){
            Write-Error "response contains error $response"
             Write-Error "$($response.UnknownResult.Error.Message)" 
        }
        else {
            # No error detected, save the response
            $response.Save("C:\Users\rtf\Desktop\Details\samplet.xml")
            Write-Host "done" -ForegroundColor Magenta
        }
     }
}
catch
{
     $_.Exception
}

You can play around with the xml code under this link.

Moerwald
  • 10,448
  • 9
  • 43
  • 83
  • 1
    I am trying the same thing. It is not stopping it and saving the file with the error only.Failed to login. – Andrew Jul 01 '19 at 04:52
  • Thanks again Moewald for your help. still script executes the else part and wrote the XML with the above message. not sure what is missing.:-( – Andrew Jul 01 '19 at 22:59
  • @Andrew please retry above code. Checked for the wrong property in `$response` – Moerwald Jul 02 '19 at 04:44