Skip to content

Commit

Permalink
Refactor to throw on API error
Browse files Browse the repository at this point in the history
  • Loading branch information
MarcL committed Mar 8, 2020
1 parent bca26fa commit 7c3f072
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 8 deletions.
2 changes: 1 addition & 1 deletion examples/excessiveRequests.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,5 @@ const broadcastOptions = {
for (let i = 0; i < 30; i += 1) {
broadcast(broadcastOptions)
.then((data) => console.log(data))
.catch((data) => console.log(data));
.catch((data) => console.log(`Error: ${data}`);
}
4 changes: 3 additions & 1 deletion src/broadcast.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,9 @@ const makeHttpRequest = (requestUrl) => {

return httpClient(requestOptions)
.then((response) => response.data.result)
.catch((error) => error.response.data.result);
.catch((error) => {
throw new Error(error.response.data.result);
});
};

const broadcast = (options) => {
Expand Down
12 changes: 6 additions & 6 deletions test/unit/broadcast.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -223,22 +223,22 @@ describe('Chatfuel.broadcast()', () => {
})
));

it('should return expected response when request fails', () => {
it('should throw expected response when request fails', () => {
const mockErrorMessage = 'Mock error message';
const error = new Error('Mock error');
error.response = {
const apiError = new Error(mockErrorMessage);
apiError.response = {
data: {
result: mockErrorMessage,
success: false,
},
};

const httpClientWithError = Promise.reject(error);
const httpClientWithError = Promise.reject(apiError);
httpClient.mockReturnValue(httpClientWithError);

return broadcast(defaultOptions)
.then((data) => {
expect(data).toEqual(mockErrorMessage);
.catch((error) => {
expect(error.toString()).toEqual(error.toString());
});
});
});

0 comments on commit 7c3f072

Please sign in to comment.