Skip to content

Commit

Permalink
Merge pull request Automattic#8986 from osher/patch-1
Browse files Browse the repository at this point in the history
fix(errors) - user defines its own r/o err.toJSON
  • Loading branch information
vkarpov15 committed May 12, 2020
2 parents b293a36 + d05dc13 commit 1bdec38
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 4 deletions.
12 changes: 8 additions & 4 deletions lib/error/validation.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,14 @@ if (util.inspect.custom) {
/*!
* Helper for JSON.stringify
*/

ValidationError.prototype.toJSON = function() {
return Object.assign({}, this, { message: this.message });
};
Object.defineProperty(ValidationError.prototype, 'toJSON', {
enumerable: false,
writable: false,
configurable: true,
value: function() {
return Object.assign({}, this, { message: this.message });
}
});

/*!
* add message
Expand Down
15 changes: 15 additions & 0 deletions test/errors.validation.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -232,4 +232,19 @@ describe('ValidationError', function() {

assert.equal(err.message, 'Validation failed');
});

describe('when user code defines a r/o Error#toJSON', function() {
it('shoud not fail', function() {
const err = [];
const child = require('child_process')
.fork('./test/isolated/project-has-error.toJSON.js', { silent: true });

child.stderr.on('data', function(buf) { err.push(buf); });
child.on('exit', function(code) {
const stderr = err.join('');
assert.equal(stderr, '');
assert.equal(code, 0);
});
});
});
});
9 changes: 9 additions & 0 deletions test/isolated/project-has-error.toJSON.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
'use strict';
Object.defineProperty(Error.prototype, 'toJSON', {
enumerable: false,
configurable: false,
writable: false,
value: () => ({ from: 'Error' })
});

require('../../');

0 comments on commit 1bdec38

Please sign in to comment.