Skip to content

fix: ParseError message handling #1619

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

Open
wants to merge 3 commits into
base: alpha
Choose a base branch
from
Open
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
18 changes: 17 additions & 1 deletion src/ParseError.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,25 @@ class ParseError extends Error {
constructor(code, message) {
super(message);
this.code = code;

const stringify = obj => {
let log = '';
for (const k in obj) {
log += `${obj[k]} `;
}
return log.trim();
};

Object.defineProperty(this, 'message', {
enumerable: true,
value: message,
value:
typeof message === 'string'
? message
: typeof message === 'object' &&
typeof message.toString === 'function' &&
!message.toString().includes('[object Object]')
? message.toString()
: stringify(message),
});
}

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

it('message can be a string', () => {
const someRandomError = 'oh no';

const error = new ParseError(1337, someRandomError);

expect(JSON.parse(JSON.stringify(error))).toEqual({
message: someRandomError,
code: 1337,
});
});

it('message can be an object passed trough some external dependency', () => {
const someRandomError = { code: '420', message: 'time to chill', status: '🎮' };

const error = new ParseError(1337, someRandomError);

expect(JSON.parse(JSON.stringify(error))).toEqual({
message: '420 time to chill 🎮',
code: 1337,
});
});

it('message can be an Error instance *receiving a string* passed trough some external dependency', () => {
const someRandomError = new Error('good point');

const error = new ParseError(1337, someRandomError);

expect(JSON.parse(JSON.stringify(error))).toEqual({
message: 'Error: good point',
code: 1337,
});
});

it('message can be an Error instance *receiving an object* passed trough some external dependency', () => {
const someRandomErrorWrong = new Error({
code: 'WRONG',
message: 'this is not how errors should be handled',
});

const error = new ParseError(1337, someRandomErrorWrong);

expect(JSON.parse(JSON.stringify(error))).toEqual({
message: '', // <-- Yeah because we can't parse errors used like that
code: 1337,
});
});
});