捕获块在节点提取中不起作用

Catch block not working in node fetch

努力学习,Javascript。请原谅,如果这真的是我所缺少的基本瘦身。

我正在尝试 运行 node-fetch 到一个错误的 url,我希望它应该被捕获并记录我的适当消息。然而,当我通过节点 运行 这个文件时,它给了我未捕获的错误

    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.

这是未捕获的部分:

 response.json()

因此为其附加一个捕获处理程序:

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

或简单地return它以便它被另一个处理程序捕获:

 return response.json()

因为您没有抛出要捕获的 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);
  });

你可以像这段代码一样用 catch 处理抓取错误

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