diff --git a/.changeset/thin-hotels-explode.md b/.changeset/thin-hotels-explode.md new file mode 100644 index 0000000000..f06b512cc5 --- /dev/null +++ b/.changeset/thin-hotels-explode.md @@ -0,0 +1,5 @@ +--- +'@backstage/errors': patch +--- + +Trim `error.cause.stack` in addition to `error.stack` when trimming stack traces from serialized errors. diff --git a/packages/errors/src/serialization/error.test.ts b/packages/errors/src/serialization/error.test.ts index a07d11749a..6418170f98 100644 --- a/packages/errors/src/serialization/error.test.ts +++ b/packages/errors/src/serialization/error.test.ts @@ -63,6 +63,20 @@ describe('serialization', () => { expect(withoutStack2.stack).not.toBeDefined(); }); + it('serializes stack traces only when allowed with error cause', () => { + const before = new CustomError('m'); + before.cause = new Error('cause'); + const withStack: any = serializeError(before, { includeStack: true }); + const withoutStack1: any = serializeError(before, { includeStack: false }); + const withoutStack2: any = serializeError(before); + expect(withStack.stack).toEqual(before.stack); + expect(withStack.cause.stack).toEqual(withStack.cause.stack); + expect(withoutStack1.stack).not.toBeDefined(); + expect(withoutStack2.stack).not.toBeDefined(); + expect(withoutStack1.cause.stack).not.toBeDefined(); + expect(withoutStack2.cause.stack).not.toBeDefined(); + }); + it('stringifies all supported forms', () => { expect(stringifyError({})).toEqual("unknown error '[object Object]'"); expect( diff --git a/packages/errors/src/serialization/error.ts b/packages/errors/src/serialization/error.ts index e48309f1e7..abdd7bf3d4 100644 --- a/packages/errors/src/serialization/error.ts +++ b/packages/errors/src/serialization/error.ts @@ -60,6 +60,14 @@ export function serializeError( if (!options?.includeStack) { delete result.stack; + + if ( + result.cause && + typeof result.cause === 'object' && + 'stack' in result.cause + ) { + delete result.cause.stack; + } } return result; diff --git a/plugins/catalog-backend/src/tests/integration.test.ts b/plugins/catalog-backend/src/tests/integration.test.ts index d278fb4f0a..737bb107ca 100644 --- a/plugins/catalog-backend/src/tests/integration.test.ts +++ b/plugins/catalog-backend/src/tests/integration.test.ts @@ -442,7 +442,6 @@ describe('Catalog Backend Integration', () => { cause: { name: 'Error', message: 'NOPE', - stack: expect.stringMatching(/^Error: NOPE/), }, }, },