Trying to learn, Javascript. Pardon if this is really a basic thin i am missing.
I am trying to run node-fetch
to a wrong url, and i expect that it should be catched and log my appropriate message. However when i run this file through node, it gives me uncatched error
JavaScript
x
21
21
1
const fetch = require('node-fetch');
2
3
fetch('http://api.icnd.com/jokes/random/10')
4
.then(response => {
5
response.json().then((data) => {
6
console.log(data)
7
});
8
}).
9
catch(error => {
10
console.log('There is some error');
11
});
12
13
14
15
(node:864) UnhandledPromiseRejectionWarning: FetchError: invalid json response body at http://api.icnd.com/jokes/random/10 reason: Unexpected token < in JSON at position 0
16
at /Users/raheel/code/js-tutorial/node_modules/node-fetch/lib/index.js:254:32
17
at <anonymous>
18
at process._tickCallback (internal/process/next_tick.js:118:7)
19
(node:864) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
20
(node:864) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
21
Advertisement
Answer
Its this part that is uncatched:
JavaScript
1
2
1
response.json()
2
Therefore attach a catch handler to it:
JavaScript
1
2
1
response.json().catch( )
2
or simply return it so that it is catched by the other handler:
JavaScript
1
2
1
return response.json()
2