Skip to content

Commit 48af62c

Browse files
committed
fix: add includeStack option to errorToJSON
1 parent d30564d commit 48af62c

File tree

2 files changed

+26
-10
lines changed

2 files changed

+26
-10
lines changed

src/__tests__/exception.test.ts

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -208,13 +208,13 @@ describe('parseStack', () => {
208208
});
209209

210210
describe('errorToJSON', () => {
211+
const cause = new RuntimeException('Something else went wrong', {
212+
details: {
213+
foo: true
214+
}
215+
});
216+
const error = new Error('Something went wrong', { cause });
211217
it('should return the expected output', () => {
212-
const cause = new RuntimeException('Something else went wrong', {
213-
details: {
214-
foo: true
215-
}
216-
});
217-
const error = new Error('Something went wrong', { cause });
218218
expect(JSON.parse(errorToJSON(error))).toStrictEqual({
219219
cause: {
220220
details: {
@@ -229,4 +229,17 @@ describe('errorToJSON', () => {
229229
stack: expect.toSatisfy((arg) => Array.isArray(arg) && arg.every((item) => typeof item === 'string'))
230230
});
231231
});
232+
it('should not include the stack, if set in the options', () => {
233+
expect(JSON.parse(errorToJSON(error, { includeStack: false }))).toStrictEqual({
234+
cause: {
235+
details: {
236+
foo: true
237+
},
238+
message: 'Something else went wrong',
239+
name: 'RuntimeException'
240+
},
241+
message: 'Something went wrong',
242+
name: 'Error'
243+
});
244+
});
232245
});

src/exception.ts

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -71,14 +71,17 @@ function parseStack(errorOrStack: Error | string | undefined): string[] {
7171
return extractStack.lines(cleanStack(stack, { pretty: true }));
7272
}
7373

74-
function errorToJSON(error: Error): string {
74+
function errorToJSON(error: Error, { includeStack = true }: { includeStack?: boolean } = {}): string {
7575
const serialize = (error: Error): { [key: string]: unknown } => {
7676
const { cause, stack, ...serialized } = serializeError(error);
77-
return {
77+
const result: { [key: string]: unknown } = {
7878
...serialized,
79-
cause: isErrorLike(cause) ? serialize(cause) : cause,
80-
stack: parseStack(stack)
79+
cause: isErrorLike(cause) ? serialize(cause) : cause
8180
};
81+
if (includeStack) {
82+
result.stack = parseStack(stack);
83+
}
84+
return result;
8285
};
8386
return JSON.stringify(serialize(error), null, 2);
8487
}

0 commit comments

Comments
 (0)