From 698f65bf7da1c33114c1eea5cd72c12b3135e95a Mon Sep 17 00:00:00 2001 From: Teddy Katz Date: Sun, 30 Jul 2017 00:19:27 -0700 Subject: [PATCH] Ensure stack is present for custom errors (fixes #351) (#360) 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 --- lib/js-yaml/exception.js | 10 +++++----- test/issues/0351.js | 17 +++++++++++++++++ test/issues/0351.yml | 4 ++++ 3 files changed, 26 insertions(+), 5 deletions(-) create mode 100644 test/issues/0351.js create mode 100644 test/issues/0351.yml diff --git a/lib/js-yaml/exception.js b/lib/js-yaml/exception.js index cf4e6252..b744a1ee 100644 --- a/lib/js-yaml/exception.js +++ b/lib/js-yaml/exception.js @@ -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 @@ -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() : ''); } diff --git a/test/issues/0351.js b/test/issues/0351.js new file mode 100644 index 00000000..58fc65a9 --- /dev/null +++ b/test/issues/0351.js @@ -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'); +}); diff --git a/test/issues/0351.yml b/test/issues/0351.yml new file mode 100644 index 00000000..8ab27b9a --- /dev/null +++ b/test/issues/0351.yml @@ -0,0 +1,4 @@ +# intentionally invalid yaml + + foo: bar +baz: qux