Skip to content

Commit a0c122b

Browse files
kmohrfsindresorhus
authored andcommitted
Gracefully handle Error instances without a stack property (#7)
1 parent 6faf669 commit a0c122b

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

index.js

+9-1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ const indentString = require('indent-string');
33
const cleanStack = require('clean-stack');
44

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

78
class AggregateError extends Error {
89
constructor(errors) {
@@ -23,7 +24,14 @@ class AggregateError extends Error {
2324
return new Error(error);
2425
});
2526

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

test.js

+25
Original file line numberDiff line numberDiff line change
@@ -26,3 +26,28 @@ test('main', t => {
2626
Object.assign(new Error(), {code: 'EQUX'})
2727
]);
2828
});
29+
30+
test('gracefully handle Error instances without a stack', t => {
31+
class StacklessError extends Error {
32+
constructor(...args) {
33+
super(...args);
34+
this.name = this.constructor.name;
35+
delete this.stack;
36+
}
37+
}
38+
39+
const error = new AggregateError([
40+
new Error('foo'),
41+
new StacklessError('stackless')
42+
]);
43+
44+
console.log(error);
45+
46+
t.regex(error.message, /Error: foo\n {8}at /);
47+
t.regex(error.message, /StacklessError: stackless/);
48+
49+
t.deepEqual([...error], [
50+
new Error('foo'),
51+
new StacklessError('stackless')
52+
]);
53+
});

0 commit comments

Comments
 (0)