Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Gracefully handle Error instances without a stack property #7

Merged
merged 1 commit into from
Feb 28, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ const indentString = require('indent-string');
const cleanStack = require('clean-stack');

const cleanInternalStack = stack => stack.replace(/\s+at .*aggregate-error\/index.js:\d+:\d+\)?/g, '');
const isString = value => typeof value === 'string' || value instanceof String;

class AggregateError extends Error {
constructor(errors) {
Expand All @@ -23,7 +24,14 @@ class AggregateError extends Error {
return new Error(error);
});

let message = errors.map(error => cleanInternalStack(cleanStack(error.stack))).join('\n');
let message = errors
.map(error => {
// Unfortunately stack is not standardized as a property of Error instances
// which makes it necessary to explicitly check for it and its type.
// In case the stack property is missing the stringified error should be used instead.
return isString(error.stack) ? cleanInternalStack(cleanStack(error.stack)) : String(error);
})
.join('\n');
message = '\n' + indentString(message, 4);
super(message);

Expand Down
25 changes: 25 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,28 @@ test('main', t => {
Object.assign(new Error(), {code: 'EQUX'})
]);
});

test('gracefully handle Error instances without a stack', t => {
class StacklessError extends Error {
constructor(...args) {
super(...args);
this.name = this.constructor.name;
delete this.stack;
}
}

const error = new AggregateError([
new Error('foo'),
new StacklessError('stackless')
]);

console.log(error);

t.regex(error.message, /Error: foo\n {8}at /);
t.regex(error.message, /StacklessError: stackless/);

t.deepEqual([...error], [
new Error('foo'),
new StacklessError('stackless')
]);
});