Skip to content

Commit

Permalink
Merge pull request #10 from Qix-/fix-bluebird
Browse files Browse the repository at this point in the history
Add ability to modify .stack
  • Loading branch information
Qix- committed Jun 19, 2018
2 parents 002e0ff + 200af66 commit 326bfd6
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 4 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,5 @@
/node_modules/
npm-debug.log
/coverage/
yarn.lock
yarn-error.log
16 changes: 12 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,20 +51,28 @@ var errorEx = function errorEx(name, properties) {
}
});

var overwrittenStack = null;

var stackDescriptor = Object.getOwnPropertyDescriptor(this, 'stack');
var stackGetter = stackDescriptor.get;
var stackValue = stackDescriptor.value;
delete stackDescriptor.value;
delete stackDescriptor.writable;

stackDescriptor.set = function (newstack) {
overwrittenStack = newstack;
};

stackDescriptor.get = function () {
var stack = (stackGetter)
? stackGetter.call(this).split(/\r?\n+/g)
: stackValue.split(/\r?\n+/g);
var stack = (overwrittenStack || ((stackGetter)
? stackGetter.call(this)
: stackValue)).split(/\r?\n+/g);

// starting in Node 7, the stack builder caches the message.
// just replace it.
stack[0] = this.name + ': ' + this.message;
if (!overwrittenStack) {
stack[0] = this.name + ': ' + this.message;
}

var lineCount = 1;
for (var key in properties) {
Expand Down
28 changes: 28 additions & 0 deletions test/test.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -124,3 +124,31 @@ describe 'helpers', ->
err.fileName = '/a/b/c/foo.txt'
testLine = err.stack.toString().split(/\r?\n/g)[1]
testLine.should.equal ' in /a/b/c/foo.txt'

describe 'bluebird support', ->
it 'should pass the bluebird stack write test', ->
bluebirdPropertyWritable = (obj, prop)->
descriptor = Object.getOwnPropertyDescriptor(obj, prop)
return !!(!descriptor || descriptor.writable || descriptor.set)

TestError = errorEx 'TestError', fileName: errorEx.line 'in %s'
err = new TestError 'error'
err_native = new Error 'hello'

(bluebirdPropertyWritable err_native, 'stack').should.be.ok()
(bluebirdPropertyWritable err, 'stack').should.be.ok()

it 'should allow the stack to be set while preserving custom properties', ->
TestError = errorEx 'TestError', fileName: errorEx.line 'in %s'

err = new TestError 'error'
err.fileName = '/a/b/c/foo.txt'
testLine = err.stack.toString().split(/\r?\n/g)[1]
testLine.should.equal ' in /a/b/c/foo.txt'

err.stack = 'TestError: overridden error\n at null:1:1'
err.stack.toString().should.equal 'TestError: overridden error\n in /a/b/c/foo.txt\n at null:1:1'

err.stack = null
testLine = err.stack.toString().split(/\r?\n/g)[1]
testLine.should.equal ' in /a/b/c/foo.txt'

0 comments on commit 326bfd6

Please sign in to comment.