Friday, 22 December 2017

Node.js | Error conventions

In node.js, it is considered the standard practice to handle errors in asynchronous functions by returning them as the first argument to the current function's callback. If there is an error, the first parameter is passed an Error object with all the details. Otherwise, the first parameter is null.

var isTrue = function(value, callback) {
     if (value === true) {
           callback(null, "Value was true.");
     } else {
           callback(new Error("Value is not true!"));
     }
}

var callback = function(error, retval) {
     if (error) {
           console.log(error);
          return;
     }
     console.log(retval);
}

/*
 * Note: When calling the same asynchronous function twice like this, you are in
 * a race condition. You have no way of knowing for certain which callback will
 * be called first when calling the functions in this manner.
 */

isTrue(false, callback);
isTrue(true, callback);

Output
D:\node\Node>node TestNode1.js
Error: Value is not true!
    at isTrue (D:\node\Node\TestNode1.js:5:12)
    at Object.<anonymous> (D:\node\Node\TestNode1.js:23:1)
    at Module._compile (module.js:569:30)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Function.Module.runMain (module.js:605:10)
    at startup (bootstrap_node.js:158:16)
    at bootstrap_node.js:575:3
Value was true.

As we can see in above example, the callback is called with null as its first argument if there is no error. However, if there is an error, we create an Error object, which then becomes the callback's only parameter.

The callback function shows the reason for this: it allows a user to easily know whether or not an error occurred. If null was not the first argument passed on success, the user would need to check the object being returned and determine them whether or not the object constituted an error - a much more complex and less user-friendly approach.

When using callbacks, if an error comes up, pass it as the first argument. Otherwise, pass null first, and then your return arguments. On the receiving end, inside the callback function, check if the first parameter is non-null; if it is, handle it as an error.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...