Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update ensureErrorType #220

Merged
merged 1 commit into from
Feb 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading