util: add decorateErrorStack()
authorcjihrig <cjihrig@gmail.com>
Wed, 25 Nov 2015 00:52:35 +0000 (19:52 -0500)
committerMyles Borins <mborins@us.ibm.com>
Tue, 19 Jan 2016 19:52:28 +0000 (11:52 -0800)
This commit adds the decorateErrorStack() method. This function
uses the internal util's getHiddenValue() method to extract
arrow messages from error objects and attach them to the
error's stack trace.

PR-URL: https://github.com/nodejs/node/pull/4013
Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl>
lib/util.js
test/parallel/test-util-decorate-error-stack.js [new file with mode: 0644]

index 25d470f..63d1fcc 100644 (file)
@@ -901,3 +901,14 @@ exports._exceptionWithHostPort = function(err,
   }
   return ex;
 };
+
+
+exports.decorateErrorStack = function(err) {
+  if (!(isError(err) && err.stack))
+    return;
+
+  const arrow = internalUtil.getHiddenValue(err, 'arrowMessage');
+
+  if (arrow)
+    err.stack = arrow + err.stack;
+};
diff --git a/test/parallel/test-util-decorate-error-stack.js b/test/parallel/test-util-decorate-error-stack.js
new file mode 100644 (file)
index 0000000..b609ee3
--- /dev/null
@@ -0,0 +1,35 @@
+'use strict';
+const common = require('../common');
+const assert = require('assert');
+const util = require('util');
+
+assert.doesNotThrow(function() {
+  util.decorateErrorStack();
+  util.decorateErrorStack(null);
+  util.decorateErrorStack(1);
+  util.decorateErrorStack(true);
+});
+
+// Verify that a stack property is not added to non-Errors
+const obj = {};
+util.decorateErrorStack(obj);
+assert.strictEqual(obj.stack, undefined);
+
+// Verify that the stack is decorated when possible
+let err;
+
+try {
+  require('../fixtures/syntax/bad_syntax');
+} catch (e) {
+  err = e;
+  assert(!/var foo bar;/.test(err.stack));
+  util.decorateErrorStack(err);
+}
+
+assert(/var foo bar;/.test(err.stack));
+
+// Verify that the stack is unchanged when there is no arrow message
+err = new Error('foo');
+const originalStack = err.stack;
+util.decorateErrorStack(err);
+assert.strictEqual(originalStack, err.stack);