Search code examples
javascriptnode.jsexpresserror-handlingthrow

halting after errors happen in catch


I recently read about it is a good practice to write throw error when an error appears in order to stop dealing with the errant results. I am not sure if whether it applies to the server of a web app built with node.js and express. Should I handle all the .catch with throw error. Would throw error causes my app to crash?


Solution

  • The catch block is where you handle the error. In other words, this is where you could potentially trigger an alternate result from the function. Example:

    try {
      const result = await fetchSomeData();
      if(result !== null) {  
        return result;
      }else{
        throw "nothing was fetched"
      }
    } catch(error) {
      console.log(error);
      const result = { error: "a custom error message", function: customCallBack };
      return result;
    }