Skip to content

Commit 92cb1a5

Browse files
committed
Merge branch 'fix/ParseError' into release/0.0.1
2 parents f8e611c + 09c54c6 commit 92cb1a5

File tree

2 files changed

+58
-4
lines changed

2 files changed

+58
-4
lines changed

src/ParseError.js

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,25 @@ class ParseError extends Error {
2020
constructor(code, message) {
2121
super(message);
2222
this.code = code;
23+
24+
const stringify = obj => {
25+
let log = '';
26+
for (const k in obj) {
27+
log += `${obj[k]} `;
28+
}
29+
return log.trim();
30+
};
31+
2332
Object.defineProperty(this, 'message', {
2433
enumerable: true,
25-
value: typeof message === 'string' ? message : JSON.stringify(message),
34+
value:
35+
typeof message === 'string'
36+
? message
37+
: typeof message === 'object' &&
38+
typeof message.toString === 'function' &&
39+
!message.toString().includes('[object Object]')
40+
? message.toString()
41+
: stringify(message),
2642
});
2743
}
2844

src/__tests__/ParseError-test.js

Lines changed: 41 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,49 @@ describe('ParseError', () => {
2828
});
2929
});
3030

31-
it('message must be a string', () => {
32-
const someRandomError = { code: 420, message: 'time to chill' };
31+
it('message can be a string', () => {
32+
const someRandomError = 'oh no';
33+
34+
const error = new ParseError(1337, someRandomError);
35+
36+
expect(JSON.parse(JSON.stringify(error))).toEqual({
37+
message: someRandomError,
38+
code: 1337,
39+
});
40+
});
41+
42+
it('message can be an object passed trough some external dependency', () => {
43+
const someRandomError = { code: '420', message: 'time to chill', status: '🎮' };
44+
45+
const error = new ParseError(1337, someRandomError);
46+
47+
expect(JSON.parse(JSON.stringify(error))).toEqual({
48+
message: '420 time to chill 🎮',
49+
code: 1337,
50+
});
51+
});
52+
53+
it('message can be an Error instance *receiving a string* passed trough some external dependency', () => {
54+
const someRandomError = new Error('good point');
55+
3356
const error = new ParseError(1337, someRandomError);
57+
58+
expect(JSON.parse(JSON.stringify(error))).toEqual({
59+
message: 'Error: good point',
60+
code: 1337,
61+
});
62+
});
63+
64+
it('message can be an Error instance *receiving an object* passed trough some external dependency', () => {
65+
const someRandomErrorWrong = new Error({
66+
code: 'WRONG',
67+
message: 'this is not how errors should be handled',
68+
});
69+
70+
const error = new ParseError(1337, someRandomErrorWrong);
71+
3472
expect(JSON.parse(JSON.stringify(error))).toEqual({
35-
message: JSON.stringify(someRandomError),
73+
message: '', // <-- Yeah because we can't parse errors used like that
3674
code: 1337,
3775
});
3876
});

0 commit comments

Comments
 (0)