Catch块在节点提取中不起作用

时间:2018-03-31 13:19:29

标签: javascript ecmascript-6 node-fetch

尝试学习,Javascript。请原谅,如果这真的是一个基本的薄我错过了。

我正在尝试将node-fetch运行到错误的网址,我希望它应该被捕获并记录我的相应消息。但是,当我通过节点运行此文件时,它会给我带来未捕获的错误

    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.

3 个答案:

答案 0 :(得分:3)

这部分未被捕获:

 response.json()

因此,请为其附加一个catch处理程序:

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

或者只是将其返回以便由其他处理程序捕获:

 return response.json()

答案 1 :(得分:2)

因为你没有为catch块抛出一个特定的错误。

&#13;
&#13;
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);
  });
&#13;
&#13;
&#13;

答案 2 :(得分:0)

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

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