Skip to content

Commit

Permalink
Update ensureErrorType (#220)
Browse files Browse the repository at this point in the history
  • Loading branch information
castrodd committed Feb 14, 2024
1 parent de87cbe commit c4bb294
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,20 @@ export class ReadOnlyError extends AzFuncTypeError {

export function ensureErrorType(err: unknown): Error & Partial<AzFuncError> {
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;
Expand Down
19 changes: 19 additions & 0 deletions test/errors.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down

0 comments on commit c4bb294

Please sign in to comment.