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

feat!: parse json error response #67

Merged
merged 3 commits into from
Jan 9, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
55 changes: 38 additions & 17 deletions src/wrapper.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,24 +119,45 @@ describe('RequestWrapper', function() {
expect(requestArgument.httpsAgent).to.eql(agents.httpsAgent);
});

it('should throw error when response code is 400 or above', async () => {
requestGetStub.restore();
nock('http://very.host.io:443')
.get('/purchases/1/content')
.reply(400, { replyText: 'Unknown route' });
context('error responses', () => {
it('should return JSON in EscherRequestError if response data is json parsable', async () => {
requestGetStub.restore();
nock('http://very.host.io:443')
.get('/purchases/1/content')
.reply(400, { replyText: 'Unknown route' }, { 'Content-Type': 'application/json; charset=utf-8' });

try {
await wrapper.send();
throw new Error('Error should have been thrown');
} catch (err) {
const error = err as EscherRequestError;
expect(error).to.be.an.instanceof(EscherRequestError);
expect(error.message).to.eql('Error in http response (status: 400)');
expect(error.code).to.eql(400);
expect(error.data).to.eql(JSON.stringify({ replyText: 'Unknown route' }));
}
try {
await wrapper.send();
throw new Error('Error should have been thrown');
} catch (err) {
const error = err as EscherRequestError;
expect(error).to.be.an.instanceof(EscherRequestError);
expect(error.message).to.eql('Error in http response (status: 400)');
expect(error.code).to.eql(400);
expect(error.data).to.eql({ replyText: 'Unknown route' });
}
});

it('should return text and not fail parsing response data if wrong content-type headers are set', async () => {
requestGetStub.restore();
nock('http://very.host.io:443')
.get('/purchases/1/content')
.reply(500, 'Unexpected Error', { 'Content-Type': 'application/json; charset=utf-8' });

try {
await wrapper.send();
throw new Error('Error should have been thrown');
} catch (err) {
const error = err as EscherRequestError;
expect(error).to.be.an.instanceof(EscherRequestError);
expect(error.message).to.eql('Error in http response (status: 500)');
expect(error.code).to.eql(500);
expect(error.data).to.eql('Unexpected Error');
}
});
});


describe('when empty response is allowed', function() {
beforeEach(function() {
extendedRequestOptions.allowEmptyResponse = true;
Expand Down Expand Up @@ -216,7 +237,7 @@ describe('RequestWrapper', function() {
expect(error).to.be.an.instanceOf(EscherRequestError);
expect(error.code).to.eql(404);
expect(error.message).to.eql('Error in http response (status: 404)');
expect(error.data).to.eql(JSON.stringify({ replyText: '404 Not Found' }));
expect(error.data).to.eql({ replyText: '404 Not Found' });
}
});
});
Expand Down Expand Up @@ -340,7 +361,7 @@ describe('RequestWrapper', function() {
expect(error).to.be.an.instanceOf(EscherRequestError);
expect(error.code).to.eql(404);
expect(error.message).to.eql('Error in http response (status: 404)');
expect(error.data).to.eql(JSON.stringify({ replyText: '404 Not Found' }));
expect(error.data).to.eql({ replyText: '404 Not Found' });
}
});

Expand Down
28 changes: 24 additions & 4 deletions src/wrapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,10 +109,22 @@ export class RequestWrapper {
code: error.response.status,
reply_text: (error.response?.data || '')
}));
let data = '';
if (error.response != null &&
this.isJsonResponse(error.response) &&
error.response.data != null &&
typeof error.response.data === 'string') {
try {
data = JSON.parse(error.response.data);
} catch (_) {
data = error.response.data;
}
}

throw new EscherRequestError(
'Error in http response (status: ' + error.response.status + ')',
error.response.status,
(error.response?.data || '') as string
data
);
} else {
if (!axios.isCancel(error)) {
Expand Down Expand Up @@ -142,9 +154,17 @@ export class RequestWrapper {
};
}

private isJsonResponse(response: TransformedResponse) {
return response.headers['content-type'] &&
response.headers['content-type'].indexOf('application/json') !== -1;
private isJsonResponse<T extends TransformedResponse | AxiosResponse>(response: T) {
let headers: RawAxiosResponseHeaders | AxiosResponseHeaders = {};
boristomic marked this conversation as resolved.
Show resolved Hide resolved
Object.assign(headers, response.headers);
headers = Object.entries(response.headers)
.reduce((acc: RawAxiosResponseHeaders | AxiosResponseHeaders, [key, val]) => {
acc[key.toLowerCase()] = val.toLowerCase();
return acc;
}, ({}));

return headers['content-type'] &&
headers['content-type'].indexOf('application/json') !== -1;
}

private getLogParameters(extraParametersToLog = {}) {
Expand Down
Loading