Error handling for a simple 'fetch some data, then save the data' Node function











up vote
0
down vote

favorite












This is a fairly simple bit of code:



async function fetchData() {
console.log("fetching data");
let json;
try {
const data = await fetch(endPoint);
json = await data.json();
}
catch (error) {
console.error(error);
handleError(error);
}

try {
await saveData(json);
} catch (error) {
console.error(error);
handleError(error);
}
}

console.info("start running");
setInterval(fetchData, config.newsapi.polling_interval);
console.info("application is running");


What we're doing is - every 15 minutes or so, we're polling an API endpoint, and then saving the results into a database.



So there's two main kinds of errors we might get here:




  • The API I fetched the data from might return some kind of error - it might be down, or my API key might be wrong, or I've gone over the rate limit or whatever.

  • The database might return some kind of error. For all the same reasons, but a completely different service.


Now in terms of handling these errors, for now all I'll be doing is logging the error, and send me an email.



But I can imagine, that in the future, I might want to handle these two distinct kinds of errors differently. As such, I've created two different try catch blocks, that gives me the flexibility to handle them differently.



But it does look a bit messier, in my opinion. The other way I could write this is:



async function fetchData() {
console.log("fetching data");
try {
const data = await fetch(endPoint);
const json = await data.json();
await saveData(json);
}
catch (error) {
console.error(error);
handleError(error);
}

}

console.info("start running");
setInterval(fetchData, config.newsapi.polling_interval);
console.info("application is running");


This looks so much tidier. But in which case - it seems like the error handling is a bit trickier.



I guess I could put a switch statement in the catch block handle different errors differently, but is that a bit messy? Any suggestions or guidelines for navigating this?










share|improve this question
















bumped to the homepage by Community 3 hours ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.



















    up vote
    0
    down vote

    favorite












    This is a fairly simple bit of code:



    async function fetchData() {
    console.log("fetching data");
    let json;
    try {
    const data = await fetch(endPoint);
    json = await data.json();
    }
    catch (error) {
    console.error(error);
    handleError(error);
    }

    try {
    await saveData(json);
    } catch (error) {
    console.error(error);
    handleError(error);
    }
    }

    console.info("start running");
    setInterval(fetchData, config.newsapi.polling_interval);
    console.info("application is running");


    What we're doing is - every 15 minutes or so, we're polling an API endpoint, and then saving the results into a database.



    So there's two main kinds of errors we might get here:




    • The API I fetched the data from might return some kind of error - it might be down, or my API key might be wrong, or I've gone over the rate limit or whatever.

    • The database might return some kind of error. For all the same reasons, but a completely different service.


    Now in terms of handling these errors, for now all I'll be doing is logging the error, and send me an email.



    But I can imagine, that in the future, I might want to handle these two distinct kinds of errors differently. As such, I've created two different try catch blocks, that gives me the flexibility to handle them differently.



    But it does look a bit messier, in my opinion. The other way I could write this is:



    async function fetchData() {
    console.log("fetching data");
    try {
    const data = await fetch(endPoint);
    const json = await data.json();
    await saveData(json);
    }
    catch (error) {
    console.error(error);
    handleError(error);
    }

    }

    console.info("start running");
    setInterval(fetchData, config.newsapi.polling_interval);
    console.info("application is running");


    This looks so much tidier. But in which case - it seems like the error handling is a bit trickier.



    I guess I could put a switch statement in the catch block handle different errors differently, but is that a bit messy? Any suggestions or guidelines for navigating this?










    share|improve this question
















    bumped to the homepage by Community 3 hours ago


    This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.

















      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      This is a fairly simple bit of code:



      async function fetchData() {
      console.log("fetching data");
      let json;
      try {
      const data = await fetch(endPoint);
      json = await data.json();
      }
      catch (error) {
      console.error(error);
      handleError(error);
      }

      try {
      await saveData(json);
      } catch (error) {
      console.error(error);
      handleError(error);
      }
      }

      console.info("start running");
      setInterval(fetchData, config.newsapi.polling_interval);
      console.info("application is running");


      What we're doing is - every 15 minutes or so, we're polling an API endpoint, and then saving the results into a database.



      So there's two main kinds of errors we might get here:




      • The API I fetched the data from might return some kind of error - it might be down, or my API key might be wrong, or I've gone over the rate limit or whatever.

      • The database might return some kind of error. For all the same reasons, but a completely different service.


      Now in terms of handling these errors, for now all I'll be doing is logging the error, and send me an email.



      But I can imagine, that in the future, I might want to handle these two distinct kinds of errors differently. As such, I've created two different try catch blocks, that gives me the flexibility to handle them differently.



      But it does look a bit messier, in my opinion. The other way I could write this is:



      async function fetchData() {
      console.log("fetching data");
      try {
      const data = await fetch(endPoint);
      const json = await data.json();
      await saveData(json);
      }
      catch (error) {
      console.error(error);
      handleError(error);
      }

      }

      console.info("start running");
      setInterval(fetchData, config.newsapi.polling_interval);
      console.info("application is running");


      This looks so much tidier. But in which case - it seems like the error handling is a bit trickier.



      I guess I could put a switch statement in the catch block handle different errors differently, but is that a bit messy? Any suggestions or guidelines for navigating this?










      share|improve this question















      This is a fairly simple bit of code:



      async function fetchData() {
      console.log("fetching data");
      let json;
      try {
      const data = await fetch(endPoint);
      json = await data.json();
      }
      catch (error) {
      console.error(error);
      handleError(error);
      }

      try {
      await saveData(json);
      } catch (error) {
      console.error(error);
      handleError(error);
      }
      }

      console.info("start running");
      setInterval(fetchData, config.newsapi.polling_interval);
      console.info("application is running");


      What we're doing is - every 15 minutes or so, we're polling an API endpoint, and then saving the results into a database.



      So there's two main kinds of errors we might get here:




      • The API I fetched the data from might return some kind of error - it might be down, or my API key might be wrong, or I've gone over the rate limit or whatever.

      • The database might return some kind of error. For all the same reasons, but a completely different service.


      Now in terms of handling these errors, for now all I'll be doing is logging the error, and send me an email.



      But I can imagine, that in the future, I might want to handle these two distinct kinds of errors differently. As such, I've created two different try catch blocks, that gives me the flexibility to handle them differently.



      But it does look a bit messier, in my opinion. The other way I could write this is:



      async function fetchData() {
      console.log("fetching data");
      try {
      const data = await fetch(endPoint);
      const json = await data.json();
      await saveData(json);
      }
      catch (error) {
      console.error(error);
      handleError(error);
      }

      }

      console.info("start running");
      setInterval(fetchData, config.newsapi.polling_interval);
      console.info("application is running");


      This looks so much tidier. But in which case - it seems like the error handling is a bit trickier.



      I guess I could put a switch statement in the catch block handle different errors differently, but is that a bit messy? Any suggestions or guidelines for navigating this?







      javascript node.js error-handling asynchronous






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Sep 15 at 15:34









      Jamal

      30.2k11115226




      30.2k11115226










      asked Sep 15 at 3:54









      dwjohnston

      646515




      646515





      bumped to the homepage by Community 3 hours ago


      This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.







      bumped to the homepage by Community 3 hours ago


      This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.
























          2 Answers
          2






          active

          oldest

          votes

















          up vote
          0
          down vote













          In my opinion it is much better to place the saveData call inside the first try-catch block.



          This avoids calling saveData with an undefined value in case an exception occurs in calls to fetch or data.json, and gives the json variable a clean scope.



          Depending on the granularity needed for error handling I would prefer to surround



          await saveData(json);


          with try-catch if necessary. However, a switch statement could also be a natural approach if you have a clear distinction on the exceptions thrown (e.g. error numbers).






          share|improve this answer




























            up vote
            0
            down vote














            Promise.catch for errors



            Why use an async function at all?



            You are using an interval that ignores the promise returned by the async fetchData, so you are not interested in whether or not the get and post succeed, you just want to report errors as they happen.



            Promises have a catch callback that is called when there is an error. Simply redirect the error passed to the catch to your handleError function.



            That way you can handle the errors in the functions who's role is appropriate rather than have fetchData handle both the get or post errors



            function postData(data) {
            const url = ????;
            const options = {
            method: "POST",
            body: JSON.stringify(data),
            headers: {"Content-Type": "application/json"}
            };
            fetch(url, options).catch(handleError);
            }

            function getData() {
            fetch(endPoint)
            .then(data => { data.json().then(postData) }) //assumes JSON is reliably formated
            .catch(handleError);
            }

            setInterval(getData, config.newsapi.polling_interval);





            share|improve this answer





















              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: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: null,
              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%2fcodereview.stackexchange.com%2fquestions%2f203766%2ferror-handling-for-a-simple-fetch-some-data-then-save-the-data-node-function%23new-answer', 'question_page');
              }
              );

              Post as a guest
































              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes








              up vote
              0
              down vote













              In my opinion it is much better to place the saveData call inside the first try-catch block.



              This avoids calling saveData with an undefined value in case an exception occurs in calls to fetch or data.json, and gives the json variable a clean scope.



              Depending on the granularity needed for error handling I would prefer to surround



              await saveData(json);


              with try-catch if necessary. However, a switch statement could also be a natural approach if you have a clear distinction on the exceptions thrown (e.g. error numbers).






              share|improve this answer

























                up vote
                0
                down vote













                In my opinion it is much better to place the saveData call inside the first try-catch block.



                This avoids calling saveData with an undefined value in case an exception occurs in calls to fetch or data.json, and gives the json variable a clean scope.



                Depending on the granularity needed for error handling I would prefer to surround



                await saveData(json);


                with try-catch if necessary. However, a switch statement could also be a natural approach if you have a clear distinction on the exceptions thrown (e.g. error numbers).






                share|improve this answer























                  up vote
                  0
                  down vote










                  up vote
                  0
                  down vote









                  In my opinion it is much better to place the saveData call inside the first try-catch block.



                  This avoids calling saveData with an undefined value in case an exception occurs in calls to fetch or data.json, and gives the json variable a clean scope.



                  Depending on the granularity needed for error handling I would prefer to surround



                  await saveData(json);


                  with try-catch if necessary. However, a switch statement could also be a natural approach if you have a clear distinction on the exceptions thrown (e.g. error numbers).






                  share|improve this answer












                  In my opinion it is much better to place the saveData call inside the first try-catch block.



                  This avoids calling saveData with an undefined value in case an exception occurs in calls to fetch or data.json, and gives the json variable a clean scope.



                  Depending on the granularity needed for error handling I would prefer to surround



                  await saveData(json);


                  with try-catch if necessary. However, a switch statement could also be a natural approach if you have a clear distinction on the exceptions thrown (e.g. error numbers).







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Sep 15 at 17:54









                  aventurin

                  34519




                  34519
























                      up vote
                      0
                      down vote














                      Promise.catch for errors



                      Why use an async function at all?



                      You are using an interval that ignores the promise returned by the async fetchData, so you are not interested in whether or not the get and post succeed, you just want to report errors as they happen.



                      Promises have a catch callback that is called when there is an error. Simply redirect the error passed to the catch to your handleError function.



                      That way you can handle the errors in the functions who's role is appropriate rather than have fetchData handle both the get or post errors



                      function postData(data) {
                      const url = ????;
                      const options = {
                      method: "POST",
                      body: JSON.stringify(data),
                      headers: {"Content-Type": "application/json"}
                      };
                      fetch(url, options).catch(handleError);
                      }

                      function getData() {
                      fetch(endPoint)
                      .then(data => { data.json().then(postData) }) //assumes JSON is reliably formated
                      .catch(handleError);
                      }

                      setInterval(getData, config.newsapi.polling_interval);





                      share|improve this answer

























                        up vote
                        0
                        down vote














                        Promise.catch for errors



                        Why use an async function at all?



                        You are using an interval that ignores the promise returned by the async fetchData, so you are not interested in whether or not the get and post succeed, you just want to report errors as they happen.



                        Promises have a catch callback that is called when there is an error. Simply redirect the error passed to the catch to your handleError function.



                        That way you can handle the errors in the functions who's role is appropriate rather than have fetchData handle both the get or post errors



                        function postData(data) {
                        const url = ????;
                        const options = {
                        method: "POST",
                        body: JSON.stringify(data),
                        headers: {"Content-Type": "application/json"}
                        };
                        fetch(url, options).catch(handleError);
                        }

                        function getData() {
                        fetch(endPoint)
                        .then(data => { data.json().then(postData) }) //assumes JSON is reliably formated
                        .catch(handleError);
                        }

                        setInterval(getData, config.newsapi.polling_interval);





                        share|improve this answer























                          up vote
                          0
                          down vote










                          up vote
                          0
                          down vote










                          Promise.catch for errors



                          Why use an async function at all?



                          You are using an interval that ignores the promise returned by the async fetchData, so you are not interested in whether or not the get and post succeed, you just want to report errors as they happen.



                          Promises have a catch callback that is called when there is an error. Simply redirect the error passed to the catch to your handleError function.



                          That way you can handle the errors in the functions who's role is appropriate rather than have fetchData handle both the get or post errors



                          function postData(data) {
                          const url = ????;
                          const options = {
                          method: "POST",
                          body: JSON.stringify(data),
                          headers: {"Content-Type": "application/json"}
                          };
                          fetch(url, options).catch(handleError);
                          }

                          function getData() {
                          fetch(endPoint)
                          .then(data => { data.json().then(postData) }) //assumes JSON is reliably formated
                          .catch(handleError);
                          }

                          setInterval(getData, config.newsapi.polling_interval);





                          share|improve this answer













                          Promise.catch for errors



                          Why use an async function at all?



                          You are using an interval that ignores the promise returned by the async fetchData, so you are not interested in whether or not the get and post succeed, you just want to report errors as they happen.



                          Promises have a catch callback that is called when there is an error. Simply redirect the error passed to the catch to your handleError function.



                          That way you can handle the errors in the functions who's role is appropriate rather than have fetchData handle both the get or post errors



                          function postData(data) {
                          const url = ????;
                          const options = {
                          method: "POST",
                          body: JSON.stringify(data),
                          headers: {"Content-Type": "application/json"}
                          };
                          fetch(url, options).catch(handleError);
                          }

                          function getData() {
                          fetch(endPoint)
                          .then(data => { data.json().then(postData) }) //assumes JSON is reliably formated
                          .catch(handleError);
                          }

                          setInterval(getData, config.newsapi.polling_interval);






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Sep 16 at 6:15









                          Blindman67

                          6,3691521




                          6,3691521






























                               

                              draft saved


                              draft discarded



















































                               


                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f203766%2ferror-handling-for-a-simple-fetch-some-data-then-save-the-data-node-function%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest




















































































                              Popular posts from this blog

                              Mont Emei

                              Province de Neuquén

                              Journaliste