Skip to content

Commit b1058a3

Browse files
committed
Unit test and fix errorToProblem logic
Signed-off-by: Jeremy Ho <jujaga@gmail.com>
1 parent 2b1cfca commit b1058a3

2 files changed

Lines changed: 39 additions & 6 deletions

File tree

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,28 @@
11
const log = require('npmlog');
22
const Problem = require('api-problem');
33

4-
module.exports = function (service, e) {
4+
module.exports = function(service, e) {
55
if (e.response) {
6-
log.error(`Error from ${service}: status = ${e.response.status}, data : ${e.response.data}`);
6+
// Handle raw data
7+
let data;
8+
if (typeof e.response.data === 'string' || e.response.data instanceof String) {
9+
data = JSON.parse(e.response.data);
10+
} else {
11+
data = e.response.data;
12+
}
13+
14+
log.error(`Error from ${service}: status = ${e.response.status}, data : ${JSON.stringify(data)}`);
715
// Validation Error
816
if (e.response.status === 422) {
917
throw new Problem(e.response.status, {
10-
detail: e.response.data.detail,
11-
errors: JSON.parse(e.response.data).errors
18+
detail: data.detail,
19+
errors: data.errors
1220
});
1321
}
1422
// Something else happened but there's a response
15-
throw new Problem(e.response.status, {detail: e.response.data.toString()});
23+
throw new Problem(e.response.status, { detail: e.response.data.toString() });
1624
} else {
1725
log.error(`Unknown error calling ${service}: ${e.message}`);
18-
throw new Problem(502, `Unknown ${service} Error`, {detail: e.message});
26+
throw new Problem(502, `Unknown ${service} Error`, { detail: e.message });
1927
}
2028
};
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
const errorToProblem = require('../../../src/components/errorToProblem');
2+
const helper = require('../../common/helper');
3+
4+
const SERVICE = 'TESTSERVICE';
5+
6+
helper.logHelper();
7+
8+
describe('errorToProblem', () => {
9+
it('should throw a 422', () => {
10+
const e = {
11+
response: {
12+
data: { detail: 'detail' },
13+
status: 422
14+
}
15+
};
16+
expect(() => errorToProblem(SERVICE, e)).toThrow('422');
17+
});
18+
19+
it('should throw a 502', () => {
20+
const e = {
21+
message: 'msg'
22+
};
23+
expect(() => errorToProblem(SERVICE, e)).toThrow('502');
24+
});
25+
});

0 commit comments

Comments
 (0)