Throw an error to a catch handler and ignore then functions?





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















I have a helper function:



function httpRequestHelper(body) {
return fetch(`${host}:${port}`, {
method: 'post',
body: JSON.stringify(body)
})
.then(function (response) {
if (!response.ok) {
throw Error(response.statusText);
}
return response.json();
})
.then(function(response) {
if (response.type === 'error') {
throw Error(response);
}
return response;
})
.catch(function(error) {
return error;
});
}


that I wrote to keep functions for various commands short. These functions just specify the body to be sent and what part of the response is relevant to the consumer:



function hasActiveProject() {
return httpRequestHelper({ type: 'request', cmd: 'has_active_project' })
.then(function (response) {
return response.payload.value;
})
}


I execute the various commands like this:



try {
let hasActiveProjectResponse = await otii.hasActiveProject()
console.log(hasActiveProjectResponse);
} catch (error) {
console.log(error);
}


Now the problem is that in the catch function I would expect to get the error message thrown, but instead I get error messages like:



TypeError: Cannot read property 'value' of undefined


This is because hasActiveProject() tries to extract the relevant response even when there was an error and that causes a different error that is returned to my catch (error) handler.



How can I rewrite this so that





  • hasActiveProject() remains thin

  • The catch handler receives the original error










share|improve this question





























    0















    I have a helper function:



    function httpRequestHelper(body) {
    return fetch(`${host}:${port}`, {
    method: 'post',
    body: JSON.stringify(body)
    })
    .then(function (response) {
    if (!response.ok) {
    throw Error(response.statusText);
    }
    return response.json();
    })
    .then(function(response) {
    if (response.type === 'error') {
    throw Error(response);
    }
    return response;
    })
    .catch(function(error) {
    return error;
    });
    }


    that I wrote to keep functions for various commands short. These functions just specify the body to be sent and what part of the response is relevant to the consumer:



    function hasActiveProject() {
    return httpRequestHelper({ type: 'request', cmd: 'has_active_project' })
    .then(function (response) {
    return response.payload.value;
    })
    }


    I execute the various commands like this:



    try {
    let hasActiveProjectResponse = await otii.hasActiveProject()
    console.log(hasActiveProjectResponse);
    } catch (error) {
    console.log(error);
    }


    Now the problem is that in the catch function I would expect to get the error message thrown, but instead I get error messages like:



    TypeError: Cannot read property 'value' of undefined


    This is because hasActiveProject() tries to extract the relevant response even when there was an error and that causes a different error that is returned to my catch (error) handler.



    How can I rewrite this so that





    • hasActiveProject() remains thin

    • The catch handler receives the original error










    share|improve this question

























      0












      0








      0








      I have a helper function:



      function httpRequestHelper(body) {
      return fetch(`${host}:${port}`, {
      method: 'post',
      body: JSON.stringify(body)
      })
      .then(function (response) {
      if (!response.ok) {
      throw Error(response.statusText);
      }
      return response.json();
      })
      .then(function(response) {
      if (response.type === 'error') {
      throw Error(response);
      }
      return response;
      })
      .catch(function(error) {
      return error;
      });
      }


      that I wrote to keep functions for various commands short. These functions just specify the body to be sent and what part of the response is relevant to the consumer:



      function hasActiveProject() {
      return httpRequestHelper({ type: 'request', cmd: 'has_active_project' })
      .then(function (response) {
      return response.payload.value;
      })
      }


      I execute the various commands like this:



      try {
      let hasActiveProjectResponse = await otii.hasActiveProject()
      console.log(hasActiveProjectResponse);
      } catch (error) {
      console.log(error);
      }


      Now the problem is that in the catch function I would expect to get the error message thrown, but instead I get error messages like:



      TypeError: Cannot read property 'value' of undefined


      This is because hasActiveProject() tries to extract the relevant response even when there was an error and that causes a different error that is returned to my catch (error) handler.



      How can I rewrite this so that





      • hasActiveProject() remains thin

      • The catch handler receives the original error










      share|improve this question














      I have a helper function:



      function httpRequestHelper(body) {
      return fetch(`${host}:${port}`, {
      method: 'post',
      body: JSON.stringify(body)
      })
      .then(function (response) {
      if (!response.ok) {
      throw Error(response.statusText);
      }
      return response.json();
      })
      .then(function(response) {
      if (response.type === 'error') {
      throw Error(response);
      }
      return response;
      })
      .catch(function(error) {
      return error;
      });
      }


      that I wrote to keep functions for various commands short. These functions just specify the body to be sent and what part of the response is relevant to the consumer:



      function hasActiveProject() {
      return httpRequestHelper({ type: 'request', cmd: 'has_active_project' })
      .then(function (response) {
      return response.payload.value;
      })
      }


      I execute the various commands like this:



      try {
      let hasActiveProjectResponse = await otii.hasActiveProject()
      console.log(hasActiveProjectResponse);
      } catch (error) {
      console.log(error);
      }


      Now the problem is that in the catch function I would expect to get the error message thrown, but instead I get error messages like:



      TypeError: Cannot read property 'value' of undefined


      This is because hasActiveProject() tries to extract the relevant response even when there was an error and that causes a different error that is returned to my catch (error) handler.



      How can I rewrite this so that





      • hasActiveProject() remains thin

      • The catch handler receives the original error







      javascript promise try-catch






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 16 '18 at 12:49









      user1283776user1283776

      3,6932160116




      3,6932160116
























          1 Answer
          1






          active

          oldest

          votes


















          1














          Are you sure you have an error? and response.payload is not undefined? because in this test fiddle you can see that its working as you want it to, the try catches the errors thrown inside the .then function, and doesn't continue.



          https://jsfiddle.net/8qe1sxg4/6/



          It looks like response.type is valid, so you don't have any errors thrown, can you confirm the results you get?



          UPDATE



          After some more researching, the catch function doesn't bubble to the next catch, it considered as if you already handled the error and continue as usual (with the resolved value from the catch).
          But you can simply reject again inside the .catch(), so this way your error will bubble to the try/catch:



          in httpRequestHelper():



          .catch(function(error) {
          return Promise.reject(error)
          //return error;
          });


          This will send your error to the next catch, see fiddle for example:
          https://jsfiddle.net/dcuo46qk/3/






          share|improve this answer


























          • Thanks! I played around with your example. It seems like the catch method in httpRequestHelper stopped the error from bubbling up to the outer catch part of the try ... catch block. I didn't consider that it actually makes sense for the catch method to catch an error! Here is the modified code that made me realize the problem: codepen.io/anon/pen/mQwobL It doesn't work on codepen, but I was unable to save on jsfiddle for some reason

            – user1283776
            Nov 16 '18 at 14:13











          • @user1283776 See updated answer

            – Art3mix
            Nov 16 '18 at 14:34











          • @user1283776 Please accept answer if its the correct one.

            – Art3mix
            Nov 16 '18 at 15:59












          Your Answer






          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: "1"
          };
          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',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53338271%2fthrow-an-error-to-a-catch-handler-and-ignore-then-functions%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          Are you sure you have an error? and response.payload is not undefined? because in this test fiddle you can see that its working as you want it to, the try catches the errors thrown inside the .then function, and doesn't continue.



          https://jsfiddle.net/8qe1sxg4/6/



          It looks like response.type is valid, so you don't have any errors thrown, can you confirm the results you get?



          UPDATE



          After some more researching, the catch function doesn't bubble to the next catch, it considered as if you already handled the error and continue as usual (with the resolved value from the catch).
          But you can simply reject again inside the .catch(), so this way your error will bubble to the try/catch:



          in httpRequestHelper():



          .catch(function(error) {
          return Promise.reject(error)
          //return error;
          });


          This will send your error to the next catch, see fiddle for example:
          https://jsfiddle.net/dcuo46qk/3/






          share|improve this answer


























          • Thanks! I played around with your example. It seems like the catch method in httpRequestHelper stopped the error from bubbling up to the outer catch part of the try ... catch block. I didn't consider that it actually makes sense for the catch method to catch an error! Here is the modified code that made me realize the problem: codepen.io/anon/pen/mQwobL It doesn't work on codepen, but I was unable to save on jsfiddle for some reason

            – user1283776
            Nov 16 '18 at 14:13











          • @user1283776 See updated answer

            – Art3mix
            Nov 16 '18 at 14:34











          • @user1283776 Please accept answer if its the correct one.

            – Art3mix
            Nov 16 '18 at 15:59
















          1














          Are you sure you have an error? and response.payload is not undefined? because in this test fiddle you can see that its working as you want it to, the try catches the errors thrown inside the .then function, and doesn't continue.



          https://jsfiddle.net/8qe1sxg4/6/



          It looks like response.type is valid, so you don't have any errors thrown, can you confirm the results you get?



          UPDATE



          After some more researching, the catch function doesn't bubble to the next catch, it considered as if you already handled the error and continue as usual (with the resolved value from the catch).
          But you can simply reject again inside the .catch(), so this way your error will bubble to the try/catch:



          in httpRequestHelper():



          .catch(function(error) {
          return Promise.reject(error)
          //return error;
          });


          This will send your error to the next catch, see fiddle for example:
          https://jsfiddle.net/dcuo46qk/3/






          share|improve this answer


























          • Thanks! I played around with your example. It seems like the catch method in httpRequestHelper stopped the error from bubbling up to the outer catch part of the try ... catch block. I didn't consider that it actually makes sense for the catch method to catch an error! Here is the modified code that made me realize the problem: codepen.io/anon/pen/mQwobL It doesn't work on codepen, but I was unable to save on jsfiddle for some reason

            – user1283776
            Nov 16 '18 at 14:13











          • @user1283776 See updated answer

            – Art3mix
            Nov 16 '18 at 14:34











          • @user1283776 Please accept answer if its the correct one.

            – Art3mix
            Nov 16 '18 at 15:59














          1












          1








          1







          Are you sure you have an error? and response.payload is not undefined? because in this test fiddle you can see that its working as you want it to, the try catches the errors thrown inside the .then function, and doesn't continue.



          https://jsfiddle.net/8qe1sxg4/6/



          It looks like response.type is valid, so you don't have any errors thrown, can you confirm the results you get?



          UPDATE



          After some more researching, the catch function doesn't bubble to the next catch, it considered as if you already handled the error and continue as usual (with the resolved value from the catch).
          But you can simply reject again inside the .catch(), so this way your error will bubble to the try/catch:



          in httpRequestHelper():



          .catch(function(error) {
          return Promise.reject(error)
          //return error;
          });


          This will send your error to the next catch, see fiddle for example:
          https://jsfiddle.net/dcuo46qk/3/






          share|improve this answer















          Are you sure you have an error? and response.payload is not undefined? because in this test fiddle you can see that its working as you want it to, the try catches the errors thrown inside the .then function, and doesn't continue.



          https://jsfiddle.net/8qe1sxg4/6/



          It looks like response.type is valid, so you don't have any errors thrown, can you confirm the results you get?



          UPDATE



          After some more researching, the catch function doesn't bubble to the next catch, it considered as if you already handled the error and continue as usual (with the resolved value from the catch).
          But you can simply reject again inside the .catch(), so this way your error will bubble to the try/catch:



          in httpRequestHelper():



          .catch(function(error) {
          return Promise.reject(error)
          //return error;
          });


          This will send your error to the next catch, see fiddle for example:
          https://jsfiddle.net/dcuo46qk/3/







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 16 '18 at 14:34

























          answered Nov 16 '18 at 13:43









          Art3mixArt3mix

          364110




          364110













          • Thanks! I played around with your example. It seems like the catch method in httpRequestHelper stopped the error from bubbling up to the outer catch part of the try ... catch block. I didn't consider that it actually makes sense for the catch method to catch an error! Here is the modified code that made me realize the problem: codepen.io/anon/pen/mQwobL It doesn't work on codepen, but I was unable to save on jsfiddle for some reason

            – user1283776
            Nov 16 '18 at 14:13











          • @user1283776 See updated answer

            – Art3mix
            Nov 16 '18 at 14:34











          • @user1283776 Please accept answer if its the correct one.

            – Art3mix
            Nov 16 '18 at 15:59



















          • Thanks! I played around with your example. It seems like the catch method in httpRequestHelper stopped the error from bubbling up to the outer catch part of the try ... catch block. I didn't consider that it actually makes sense for the catch method to catch an error! Here is the modified code that made me realize the problem: codepen.io/anon/pen/mQwobL It doesn't work on codepen, but I was unable to save on jsfiddle for some reason

            – user1283776
            Nov 16 '18 at 14:13











          • @user1283776 See updated answer

            – Art3mix
            Nov 16 '18 at 14:34











          • @user1283776 Please accept answer if its the correct one.

            – Art3mix
            Nov 16 '18 at 15:59

















          Thanks! I played around with your example. It seems like the catch method in httpRequestHelper stopped the error from bubbling up to the outer catch part of the try ... catch block. I didn't consider that it actually makes sense for the catch method to catch an error! Here is the modified code that made me realize the problem: codepen.io/anon/pen/mQwobL It doesn't work on codepen, but I was unable to save on jsfiddle for some reason

          – user1283776
          Nov 16 '18 at 14:13





          Thanks! I played around with your example. It seems like the catch method in httpRequestHelper stopped the error from bubbling up to the outer catch part of the try ... catch block. I didn't consider that it actually makes sense for the catch method to catch an error! Here is the modified code that made me realize the problem: codepen.io/anon/pen/mQwobL It doesn't work on codepen, but I was unable to save on jsfiddle for some reason

          – user1283776
          Nov 16 '18 at 14:13













          @user1283776 See updated answer

          – Art3mix
          Nov 16 '18 at 14:34





          @user1283776 See updated answer

          – Art3mix
          Nov 16 '18 at 14:34













          @user1283776 Please accept answer if its the correct one.

          – Art3mix
          Nov 16 '18 at 15:59





          @user1283776 Please accept answer if its the correct one.

          – Art3mix
          Nov 16 '18 at 15:59




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53338271%2fthrow-an-error-to-a-catch-handler-and-ignore-then-functions%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Bressuire

          Vorschmack

          Quarantine