Skip to content

Commit

Permalink
Handling errors
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexandreKavalerski committed Dec 28, 2017
1 parent ecc3e34 commit f603f98
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
9 changes: 8 additions & 1 deletion src/ConvertBTC.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
const request = require('request');

/* eslint consistent-return: 0 */
function convertBTC(currency = 'USD', amount = 1) {
const url = `https://apiv2.bitcoinaverage.com/convert/global?from=BTC&to=${currency}&amount=${amount}`;
request(url, (error, response, body) => {
const apiResponse = JSON.parse(body);
let apiResponse;
try {
apiResponse = JSON.parse(body);
} catch (parseError) {
console.log('Something went wrong with the API. Try in a few minutes.');
return parseError;
}
console.log(`${amount} BTC to ${currency} = ${apiResponse.price}`);
});
}
Expand Down
13 changes: 13 additions & 0 deletions tests/ConvertBTC.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,4 +62,17 @@ describe('ConvertBTC', () => {
done();
}, 300);
});

it('should message user when api reply with error', (done) => {
nock('https://apiv2.bitcoinaverage.com')
.get('/convert/global')
.query({ from: 'BTC', to: 'BRL', amount: 1 })
.replyWithError('Error');

convertBTC('BRL');
setTimeout(() => {
expect(consoleStub).to.be.calledWith('Something went wrong with the API. Try in a few minutes.');
done();
}, 300);
});
});

0 comments on commit f603f98

Please sign in to comment.