Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

npm's guidelines on callback errors

Tags:

People also ask

How do you handle errors in callback?

Error-First Callback in Node. js is a function which either returns an error object or any successful data returned by the function. The first argument in the function is reserved for the error object. If any error has occurred during the execution of the function, it will be returned by the first argument.

What are error-First callbacks?

Error-first callback in Node. js is a function that returns an error object whenever any successful data is returned by the function. The first argument is reserved for the error object by the function. This error object is returned by the first argument whenever any error occurs during the execution of the function.

How many callback functions can be executed at any time?

As long as the callback code is purely sync than no two functions can execute parallel.

What is the first argument at the asynchronous callback?

The first argument of the callback is reserved for an error object. If an error occurred, it will be returned by the first err argument. The second argument of the callback is reserved for any successful response data.


I was reading through npm’s coding style guidelines and came across the following very cryptic suggestion:

Be very careful never to ever ever throw anything. It’s worse than useless. Just send the error message back as the first argument to the callback.

What exactly do they mean and how does one implement this behavior? Do they suggest calling the callback function within itself?

Here’s what I could think of using the async fs.readdir method.

fs.readdir('./', function callback(err, files) {
  if (err) {
    // throw err  // npm says DO NOT do this!
    callback(err) // Wouldn’t this cause an infinite loop?
  }
  else {
    // normal stuff
  }
})