Skip to content

Commit 422a865

Browse files
cjihrigMyles Borins
authored and
Myles Borins
committed
util: add decorateErrorStack()
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: #4013 Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl>
1 parent 1bf84b9 commit 422a865

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

Diff for: lib/util.js

+11
Original file line numberDiff line numberDiff line change
@@ -901,3 +901,14 @@ exports._exceptionWithHostPort = function(err,
901901
}
902902
return ex;
903903
};
904+
905+
906+
exports.decorateErrorStack = function(err) {
907+
if (!(isError(err) && err.stack))
908+
return;
909+
910+
const arrow = internalUtil.getHiddenValue(err, 'arrowMessage');
911+
912+
if (arrow)
913+
err.stack = arrow + err.stack;
914+
};

Diff for: test/parallel/test-util-decorate-error-stack.js

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
'use strict';
2+
const common = require('../common');
3+
const assert = require('assert');
4+
const util = require('util');
5+
6+
assert.doesNotThrow(function() {
7+
util.decorateErrorStack();
8+
util.decorateErrorStack(null);
9+
util.decorateErrorStack(1);
10+
util.decorateErrorStack(true);
11+
});
12+
13+
// Verify that a stack property is not added to non-Errors
14+
const obj = {};
15+
util.decorateErrorStack(obj);
16+
assert.strictEqual(obj.stack, undefined);
17+
18+
// Verify that the stack is decorated when possible
19+
let err;
20+
21+
try {
22+
require('../fixtures/syntax/bad_syntax');
23+
} catch (e) {
24+
err = e;
25+
assert(!/var foo bar;/.test(err.stack));
26+
util.decorateErrorStack(err);
27+
}
28+
29+
assert(/var foo bar;/.test(err.stack));
30+
31+
// Verify that the stack is unchanged when there is no arrow message
32+
err = new Error('foo');
33+
const originalStack = err.stack;
34+
util.decorateErrorStack(err);
35+
assert.strictEqual(originalStack, err.stack);

0 commit comments

Comments
 (0)