10

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

    const fetch = require('node-fetch');

    fetch('http://api.icnd.com/jokes/random/10')
        .then(response => {
            response.json().then((data) => {
                console.log(data)
            });
        }).
        catch(error => {
            console.log('There is some error');
        });



(node:864) UnhandledPromiseRejectionWarning: FetchError: invalid json response body at http://api.icnd.com/jokes/random/10 reason: Unexpected token < in JSON at position 0
    at /Users/raheel/code/js-tutorial/node_modules/node-fetch/lib/index.js:254:32
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:118:7)
(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)
(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.
Raheel
  • 8,716
  • 9
  • 60
  • 102
  • maybe the error is in line `response.json()` when you're trying to parse json response ? because `catch` is used when the request itself failed – davidluckystar Mar 31 '18 at 13:25
  • Use `fetch(…).then(res => res.json()).then(console.log, console.error)`. – Bergi Mar 31 '18 at 13:55

4 Answers4

15

Because you are not throwing a specific error for catch block to catch.

const fetch = require('node-fetch');

fetch('http://api.icnd.com/jokes/random/10/api/1')
  .then(response => {
    if (response.ok) {
      response.json().then((data) => {
        console.log(data);
      });  
    } else {
      throw 'There is something wrong';
    }
  }).
  catch(error => {
      console.log(error);
  });
yPhil
  • 8,049
  • 4
  • 57
  • 83
10

Its this part that is uncatched:

 response.json()

Therefore attach a catch handler to it:

 response.json().catch(...)

or simply return it so that it is catched by the other handler:

 return response.json()
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
2

The proper solution is to check first if the response status code is 2xx, as the HTTP response codes outside this range are not treated as JavaScript errors (and hence not being thrown).

So before you start any parsing, you must check the ok property on the response object.

const fetch = require('node-fetch');

fetch('http://api.icnd.com/jokes/random/10')
    .then(response => {
        if (response.ok) {
            return response.json();
        } else {
            console.error(response.status, response.statusText);
            throw Error(`${response.status} - ${response.statusText}`);
        }
    })
    .then((data) => {
        console.log(data);
    })
    .catch(error => {
        console.error('There is some error', error);
    });

Reference: https://dev.to/anchobies/when-that-s-not-so-fetch-error-handling-with-fetch-4cce

Draško Kokić
  • 1,280
  • 1
  • 19
  • 34
0

you can handle fetch error with catch like this code

fetch("url").then(response=> response.json()).then(data=>{
                 res.render("index",{data:data});
        }).catch(error=>{
            //handle error here
        });