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

fix: ParseError message handling #1619

Open
wants to merge 3 commits into
base: alpha
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 8 additions & 1 deletion src/ParseError.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,14 @@ class ParseError extends Error {
this.code = code;
Object.defineProperty(this, 'message', {
enumerable: true,
value: message,
value:
typeof message === 'string'
? message
: typeof message === 'object' &&
typeof message.toString === 'function' &&
mtrezza marked this conversation as resolved.
Show resolved Hide resolved
message.toString() !== '[object Object]'
? message.toString()
: JSON.stringify(message),
});
}

Expand Down
23 changes: 23 additions & 0 deletions src/__tests__/ParseError-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,27 @@ describe('ParseError', () => {
code: 123,
});
});

it('message must be a string', () => {
/**
* error as object
stewones marked this conversation as resolved.
Show resolved Hide resolved
*/
const someRandomError = { code: 420, message: 'time to chill' };
const error = new ParseError(1337, someRandomError);
expect(JSON.parse(JSON.stringify(error))).toEqual({
message: JSON.stringify(someRandomError),
code: 1337,
});

/**
* error as an Error instance
*/
const someRandomError2 = new Error('time to relax');
const error2 = new ParseError(420, someRandomError2);

expect(JSON.parse(JSON.stringify(error2))).toEqual({
message: 'Error: time to relax',
code: 420,
});
});
});