Invoke-WebRequest in a loop until NotFound

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;







up vote
0
down vote

favorite












I'm using SAP's Raylight RESTful SDK to get a list of universes from the BusinessObject Enterprise repository.



To get all of the universes, the request needs to be called repeatedly, incrementing the offset parameter until the request returns a Not Found [404] error.



Current approach:



$baseUrl = 'http://<server>:6405/biprws/raylight/v1'

$headers = @
$headers.Add("Accept", "application/json")
$headers.Add("Content-Type", "application/json")
$headers.Add("x-sap-logontoken", $Token)

$offset = 0
$limit = 50

try
do

$Path = "/universes?offset=$offset&limit=$limit"

$response = Invoke-WebRequest "$baseUrl$Path" -Headers $headers
($response until ( $response.StatusCode -eq [System.Net.HttpStatusCode]::NotFound )

catch
# catches 404 too
Write-Debug "StatusCode: $($_.Exception.Response.StatusCode.Value__)"



While the code returns the expected results, I not sure that I like how the code will always exit via the catch. I could remove the try/catch, but that will leave the code exposed to other errors.



Is there a way to improve this?







share|improve this question

























    up vote
    0
    down vote

    favorite












    I'm using SAP's Raylight RESTful SDK to get a list of universes from the BusinessObject Enterprise repository.



    To get all of the universes, the request needs to be called repeatedly, incrementing the offset parameter until the request returns a Not Found [404] error.



    Current approach:



    $baseUrl = 'http://<server>:6405/biprws/raylight/v1'

    $headers = @
    $headers.Add("Accept", "application/json")
    $headers.Add("Content-Type", "application/json")
    $headers.Add("x-sap-logontoken", $Token)

    $offset = 0
    $limit = 50

    try
    do

    $Path = "/universes?offset=$offset&limit=$limit"

    $response = Invoke-WebRequest "$baseUrl$Path" -Headers $headers
    ($response until ( $response.StatusCode -eq [System.Net.HttpStatusCode]::NotFound )

    catch
    # catches 404 too
    Write-Debug "StatusCode: $($_.Exception.Response.StatusCode.Value__)"



    While the code returns the expected results, I not sure that I like how the code will always exit via the catch. I could remove the try/catch, but that will leave the code exposed to other errors.



    Is there a way to improve this?







    share|improve this question





















      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I'm using SAP's Raylight RESTful SDK to get a list of universes from the BusinessObject Enterprise repository.



      To get all of the universes, the request needs to be called repeatedly, incrementing the offset parameter until the request returns a Not Found [404] error.



      Current approach:



      $baseUrl = 'http://<server>:6405/biprws/raylight/v1'

      $headers = @
      $headers.Add("Accept", "application/json")
      $headers.Add("Content-Type", "application/json")
      $headers.Add("x-sap-logontoken", $Token)

      $offset = 0
      $limit = 50

      try
      do

      $Path = "/universes?offset=$offset&limit=$limit"

      $response = Invoke-WebRequest "$baseUrl$Path" -Headers $headers
      ($response until ( $response.StatusCode -eq [System.Net.HttpStatusCode]::NotFound )

      catch
      # catches 404 too
      Write-Debug "StatusCode: $($_.Exception.Response.StatusCode.Value__)"



      While the code returns the expected results, I not sure that I like how the code will always exit via the catch. I could remove the try/catch, but that will leave the code exposed to other errors.



      Is there a way to improve this?







      share|improve this question











      I'm using SAP's Raylight RESTful SDK to get a list of universes from the BusinessObject Enterprise repository.



      To get all of the universes, the request needs to be called repeatedly, incrementing the offset parameter until the request returns a Not Found [404] error.



      Current approach:



      $baseUrl = 'http://<server>:6405/biprws/raylight/v1'

      $headers = @
      $headers.Add("Accept", "application/json")
      $headers.Add("Content-Type", "application/json")
      $headers.Add("x-sap-logontoken", $Token)

      $offset = 0
      $limit = 50

      try
      do

      $Path = "/universes?offset=$offset&limit=$limit"

      $response = Invoke-WebRequest "$baseUrl$Path" -Headers $headers
      ($response until ( $response.StatusCode -eq [System.Net.HttpStatusCode]::NotFound )

      catch
      # catches 404 too
      Write-Debug "StatusCode: $($_.Exception.Response.StatusCode.Value__)"



      While the code returns the expected results, I not sure that I like how the code will always exit via the catch. I could remove the try/catch, but that will leave the code exposed to other errors.



      Is there a way to improve this?









      share|improve this question










      share|improve this question




      share|improve this question









      asked Jan 17 at 17:59









      craig

      1085




      1085




















          1 Answer
          1






          active

          oldest

          votes

















          up vote
          2
          down vote













          You appear to have some incorrect logic. The until expression will never get evaluated in the case of a 404 exception. It will get skipped over. So it's kind of pointless.



          So let's replace the repeat ... until with a while ($true). That is, an infinite loop. This works the same as what you already had, but the logic is clearer. I added a comment at the top, too, to let the reader know that a 404 exception will break the loop:



          while ($true) ConvertFrom-Json).universes.universe

          $offset += $limit



          Now, in general it's not good to use exceptions for normal program control flow. They should normally be used for exceptional cases only. But sometimes—such as in this case it would seem—we do have to use them. In such cases the usual pattern is to catch the exception and then examine it to see if it's a normal control flow exception or if it's a true exception, and respond accordingly.



          So let's do that. If we catch a 404 exception, then we will just ignore it. If it's anything else, then we will rethrow it:



          try 
          while ($true)
          # Will throw 404 exception when finished.

          $Path = "/universes?offset=$offset&limit=$limit"

          $response = Invoke-WebRequest "$baseUrl$Path" -Headers $headers
          ($response

          catch [System.Net.WebException]
          $statusCode = $_.Exception.Response.StatusCode.Value__

          if ($statusCode -eq 404)
          # Normal end case. Do nothing.

          else
          throw







          share|improve this answer























          • I considered using an infinite loop, too. I'd probably change the catch to use a switch: Switch ($_.Exception.Response.StatusCode) [System.Net.HttpStatusCode]::NotFound # nada default throw
            – craig
            Jan 18 at 13:07











          Your Answer




          StackExchange.ifUsing("editor", function ()
          return StackExchange.using("mathjaxEditing", function ()
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          );
          );
          , "mathjax-editing");

          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "196"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          convertImagesToLinks: false,
          noModals: false,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );








           

          draft saved


          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f185337%2finvoke-webrequest-in-a-loop-until-notfound%23new-answer', 'question_page');

          );

          Post as a guest






























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          2
          down vote













          You appear to have some incorrect logic. The until expression will never get evaluated in the case of a 404 exception. It will get skipped over. So it's kind of pointless.



          So let's replace the repeat ... until with a while ($true). That is, an infinite loop. This works the same as what you already had, but the logic is clearer. I added a comment at the top, too, to let the reader know that a 404 exception will break the loop:



          while ($true) ConvertFrom-Json).universes.universe

          $offset += $limit



          Now, in general it's not good to use exceptions for normal program control flow. They should normally be used for exceptional cases only. But sometimes—such as in this case it would seem—we do have to use them. In such cases the usual pattern is to catch the exception and then examine it to see if it's a normal control flow exception or if it's a true exception, and respond accordingly.



          So let's do that. If we catch a 404 exception, then we will just ignore it. If it's anything else, then we will rethrow it:



          try 
          while ($true)
          # Will throw 404 exception when finished.

          $Path = "/universes?offset=$offset&limit=$limit"

          $response = Invoke-WebRequest "$baseUrl$Path" -Headers $headers
          ($response

          catch [System.Net.WebException]
          $statusCode = $_.Exception.Response.StatusCode.Value__

          if ($statusCode -eq 404)
          # Normal end case. Do nothing.

          else
          throw







          share|improve this answer























          • I considered using an infinite loop, too. I'd probably change the catch to use a switch: Switch ($_.Exception.Response.StatusCode) [System.Net.HttpStatusCode]::NotFound # nada default throw
            – craig
            Jan 18 at 13:07















          up vote
          2
          down vote













          You appear to have some incorrect logic. The until expression will never get evaluated in the case of a 404 exception. It will get skipped over. So it's kind of pointless.



          So let's replace the repeat ... until with a while ($true). That is, an infinite loop. This works the same as what you already had, but the logic is clearer. I added a comment at the top, too, to let the reader know that a 404 exception will break the loop:



          while ($true) ConvertFrom-Json).universes.universe

          $offset += $limit



          Now, in general it's not good to use exceptions for normal program control flow. They should normally be used for exceptional cases only. But sometimes—such as in this case it would seem—we do have to use them. In such cases the usual pattern is to catch the exception and then examine it to see if it's a normal control flow exception or if it's a true exception, and respond accordingly.



          So let's do that. If we catch a 404 exception, then we will just ignore it. If it's anything else, then we will rethrow it:



          try 
          while ($true)
          # Will throw 404 exception when finished.

          $Path = "/universes?offset=$offset&limit=$limit"

          $response = Invoke-WebRequest "$baseUrl$Path" -Headers $headers
          ($response

          catch [System.Net.WebException]
          $statusCode = $_.Exception.Response.StatusCode.Value__

          if ($statusCode -eq 404)
          # Normal end case. Do nothing.

          else
          throw







          share|improve this answer























          • I considered using an infinite loop, too. I'd probably change the catch to use a switch: Switch ($_.Exception.Response.StatusCode) [System.Net.HttpStatusCode]::NotFound # nada default throw
            – craig
            Jan 18 at 13:07













          up vote
          2
          down vote










          up vote
          2
          down vote









          You appear to have some incorrect logic. The until expression will never get evaluated in the case of a 404 exception. It will get skipped over. So it's kind of pointless.



          So let's replace the repeat ... until with a while ($true). That is, an infinite loop. This works the same as what you already had, but the logic is clearer. I added a comment at the top, too, to let the reader know that a 404 exception will break the loop:



          while ($true) ConvertFrom-Json).universes.universe

          $offset += $limit



          Now, in general it's not good to use exceptions for normal program control flow. They should normally be used for exceptional cases only. But sometimes—such as in this case it would seem—we do have to use them. In such cases the usual pattern is to catch the exception and then examine it to see if it's a normal control flow exception or if it's a true exception, and respond accordingly.



          So let's do that. If we catch a 404 exception, then we will just ignore it. If it's anything else, then we will rethrow it:



          try 
          while ($true)
          # Will throw 404 exception when finished.

          $Path = "/universes?offset=$offset&limit=$limit"

          $response = Invoke-WebRequest "$baseUrl$Path" -Headers $headers
          ($response

          catch [System.Net.WebException]
          $statusCode = $_.Exception.Response.StatusCode.Value__

          if ($statusCode -eq 404)
          # Normal end case. Do nothing.

          else
          throw







          share|improve this answer















          You appear to have some incorrect logic. The until expression will never get evaluated in the case of a 404 exception. It will get skipped over. So it's kind of pointless.



          So let's replace the repeat ... until with a while ($true). That is, an infinite loop. This works the same as what you already had, but the logic is clearer. I added a comment at the top, too, to let the reader know that a 404 exception will break the loop:



          while ($true) ConvertFrom-Json).universes.universe

          $offset += $limit



          Now, in general it's not good to use exceptions for normal program control flow. They should normally be used for exceptional cases only. But sometimes—such as in this case it would seem—we do have to use them. In such cases the usual pattern is to catch the exception and then examine it to see if it's a normal control flow exception or if it's a true exception, and respond accordingly.



          So let's do that. If we catch a 404 exception, then we will just ignore it. If it's anything else, then we will rethrow it:



          try 
          while ($true)
          # Will throw 404 exception when finished.

          $Path = "/universes?offset=$offset&limit=$limit"

          $response = Invoke-WebRequest "$baseUrl$Path" -Headers $headers
          ($response

          catch [System.Net.WebException]
          $statusCode = $_.Exception.Response.StatusCode.Value__

          if ($statusCode -eq 404)
          # Normal end case. Do nothing.

          else
          throw








          share|improve this answer















          share|improve this answer



          share|improve this answer








          edited Jan 18 at 13:01


























          answered Jan 18 at 5:17









          Dangph

          1,458510




          1,458510











          • I considered using an infinite loop, too. I'd probably change the catch to use a switch: Switch ($_.Exception.Response.StatusCode) [System.Net.HttpStatusCode]::NotFound # nada default throw
            – craig
            Jan 18 at 13:07

















          • I considered using an infinite loop, too. I'd probably change the catch to use a switch: Switch ($_.Exception.Response.StatusCode) [System.Net.HttpStatusCode]::NotFound # nada default throw
            – craig
            Jan 18 at 13:07
















          I considered using an infinite loop, too. I'd probably change the catch to use a switch: Switch ($_.Exception.Response.StatusCode) [System.Net.HttpStatusCode]::NotFound # nada default throw
          – craig
          Jan 18 at 13:07





          I considered using an infinite loop, too. I'd probably change the catch to use a switch: Switch ($_.Exception.Response.StatusCode) [System.Net.HttpStatusCode]::NotFound # nada default throw
          – craig
          Jan 18 at 13:07













           

          draft saved


          draft discarded


























           


          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f185337%2finvoke-webrequest-in-a-loop-until-notfound%23new-answer', 'question_page');

          );

          Post as a guest













































































          Popular posts from this blog

          Chat program with C++ and SFML

          Function to Return a JSON Like Objects Using VBA Collections and Arrays

          Will my employers contract hold up in court?