Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

[doc] Found content not under version control.

  • Loading branch information...
commit 957be2ee94a5feca8d62a0964865271bd7681a49 1 parent edf531f
Joshua Holbrook authored November 02, 2011
39  pages/articles/errors/what-are-the-error-conventions/content.md
Source Rendered
... ...
@@ -0,0 +1,39 @@
  1
+
  2
+In node.js, it is considered 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. 
  3
+
  4
+It's simpler than it sounds; let's demonstrate.
  5
+
  6
+    var isTrue = function(value, callback) {
  7
+      if (value === true) {
  8
+        callback(null, "Value was true.");
  9
+      }
  10
+      else {
  11
+        callback(new Error("Value is not true!"));
  12
+      }
  13
+    }
  14
+
  15
+    var callback = function (error, retval) {
  16
+      if (error) {
  17
+        console.log(error);
  18
+        return;
  19
+      }
  20
+      console.log(retval);
  21
+    }
  22
+
  23
+    // Note: when calling the same asynchronous function twice like this, you are in a race condition.
  24
+    // You have no way of knowing for certain which callback will be called first when calling the functions in this manner.
  25
+
  26
+    isTrue(false, callback);
  27
+    isTrue(true,  callback);
  28
+
  29
+    { stack: [Getter/Setter],
  30
+      arguments: undefined,
  31
+      type: undefined,
  32
+      message: 'Value is not true!' }
  33
+    Value was true.
  34
+
  35
+As you can see from the example, the callback is called with null as its first argument if there is no error. However, if there is an error, you create an `Error` object, which then becomes the callback's only parameter. 
  36
+
  37
+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 themselves whether or not the object constituted an error - a much more complex and less user-friendly approach.
  38
+
  39
+So to wrap it all up, when using callbacks, if an error comes up, then 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.

0 notes on commit 957be2e

Please sign in to comment.
Something went wrong with that request. Please try again.