error handling in asynchronous node.js calls

前端 未结 10 1662
感动是毒
感动是毒 2020-12-12 19:32

I\'m new to node.js although I\'m pretty familiar with JavaScript in general. My question is regarding \"best practices\" on how to handle errors in node.js.

Normall

10条回答
  •  伪装坚强ぢ
    2020-12-12 19:53

    At the time of this writing, the approach I am seeing is to use "Promises".

    http://howtonode.org/promises
    https://www.promisejs.org/

    These allow code and callbacks to be structured well for error management and also makes it more readable. It primarily uses the .then() function.

    someFunction().then(success_callback_func, failed_callback_func);
    

    Here's a basic example:

      var SomeModule = require('someModule');
    
      var success = function (ret) {
          console.log('>>>>>>>> Success!');
      }
    
      var failed = function (err) {
        if (err instanceof SomeModule.errorName) {
          // Note: I've often seen the error definitions in SomeModule.errors.ErrorName
          console.log("FOUND SPECIFIC ERROR");
        }
        console.log('>>>>>>>> FAILED!');
      }
    
      someFunction().then(success, failed);
      console.log("This line with appear instantly, since the last function was asynchronous.");
    

提交回复
热议问题