From a73bde1fe8546298644c4ce9de52927fee1e4f98 Mon Sep 17 00:00:00 2001 From: Daniel Castro Date: Tue, 13 Feb 2024 15:44:51 -0800 Subject: [PATCH] Update ensureErrorType --- src/errors.ts | 14 ++++++++++++++ test/errors.test.ts | 19 +++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/src/errors.ts b/src/errors.ts index 78e3642..b2db275 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -29,6 +29,20 @@ export class ReadOnlyError extends AzFuncTypeError { export function ensureErrorType(err: unknown): Error & Partial { if (err instanceof Error) { + const writable = Object.getOwnPropertyDescriptor(err, 'message')?.writable; + if (!writable) { + // The motivation for this branch can be found in the below issue: + // https://github.com/Azure/azure-functions-nodejs-library/issues/205 + let readableMessage = err.message; + Object.defineProperty(err, 'message', { + get() { + return readableMessage; + }, + set(val: string) { + readableMessage = val; + }, + }); + } return err; } else { let message: string; diff --git a/test/errors.test.ts b/test/errors.test.ts index 7e13cd1..67dc2f9 100644 --- a/test/errors.test.ts +++ b/test/errors.test.ts @@ -42,6 +42,25 @@ describe('ensureErrorType', () => { expect(ensureErrorType(actualError)).to.equal(actualError); }); + it('readonly error', () => { + class ReadOnlyError extends Error { + get message(): string { + return 'a readonly message'; + } + } + + const actualError = new ReadOnlyError(); + + // @ts-expect-error: create a function to test that writing throws an exception + expect(() => (actualError.message = 'exception')).to.throw(); + + const wrappedError = ensureErrorType(actualError); + wrappedError.message = 'Readonly error has been modified'; + + expect(wrappedError.message).to.equal('Readonly error has been modified'); + expect(wrappedError.stack).to.contain('Readonly error has been modified'); + }); + function validateError(actual: Error, expectedMessage: string): void { expect(actual).to.be.instanceof(Error); expect(actual.message).to.equal(expectedMessage);