Catch block not working in node fetch
Asked Answered
O

4

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.
Olympia answered 31/3, 2018 at 13:19 Comment(2)
maybe the error is in line response.json() when you're trying to parse json response ? because catch is used when the request itself failedBassarisk
Use fetch(…).then(res => res.json()).then(console.log, console.error).Rinarinaldi
Z
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()
Zigzagger answered 31/3, 2018 at 13:24 Comment(0)
F
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);
  });
Fleenor answered 31/3, 2018 at 13:40 Comment(0)
Z
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()
Zigzagger answered 31/3, 2018 at 13:24 Comment(0)
T
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

Templia answered 26/11, 2022 at 11:22 Comment(0)
Z
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
        });
Zelikow answered 19/12, 2020 at 8:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.