Skip to content
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,
});
});
});