Skip to content

Commit

Permalink
Ensure stack is present for custom errors (fixes #351) (#360)
Browse files Browse the repository at this point in the history
Starting in Node 7, stack traces are computed eagerly when using Error.captureStackTrace [1]. As a result, the `message` and `name` properties of an error will not be included in the `stack` property if they are set after calling `Error.captureStackTrace`. As a workaround, set the properties before calling `Error.captureStackTrace`.

Note that this change in Node was reverted in V8 a few days ago [2], but it will probably be awhile until that fix appears in a Node release.

[1] https://chromium.googlesource.com/v8/v8.git/+/4feafee9d9741259e8ec3882fb61935a235ecc54
[2] https://chromium.googlesource.com/v8/v8.git/+/989d7b96f8352b502e2ede62e0b105e143d03837
  • Loading branch information
not-an-aardvark authored and Vitaly Puzrin committed Jul 30, 2017
1 parent d411edd commit 698f65b
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 5 deletions.
10 changes: 5 additions & 5 deletions lib/js-yaml/exception.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ function YAMLException(reason, mark) {
// Super constructor
Error.call(this);

this.name = 'YAMLException';
this.reason = reason;
this.mark = mark;
this.message = (this.reason || '(unknown reason)') + (this.mark ? ' ' + this.mark.toString() : '');

// Include stack trace in error object
if (Error.captureStackTrace) {
// Chrome and NodeJS
Expand All @@ -14,11 +19,6 @@ function YAMLException(reason, mark) {
// FF, IE 10+ and Safari 6+. Fallback for others
this.stack = (new Error()).stack || '';
}

this.name = 'YAMLException';
this.reason = reason;
this.mark = mark;
this.message = (this.reason || '(unknown reason)') + (this.mark ? ' ' + this.mark.toString() : '');
}


Expand Down
17 changes: 17 additions & 0 deletions test/issues/0351.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
'use strict';


var assert = require('assert');
var yaml = require('../..');
var readFileSync = require('fs').readFileSync;


test('should include the error message in the error stack', function () {
try {
yaml.safeLoad(readFileSync(require('path').join(__dirname, '/0351.yml'), 'utf8'));
} catch (err) {
assert(err.stack.startsWith('YAMLException: end of the stream or a document separator is expected'));
return;
}
assert.fail(null, null, 'Expected an error to be thrown');
});
4 changes: 4 additions & 0 deletions test/issues/0351.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# intentionally invalid yaml

foo: bar
baz: qux

0 comments on commit 698f65b

Please sign in to comment.