javascript - 捕获 block 在节点提取中不起作用

标签 javascript ecmascript-6 node-fetch

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

我正在尝试运行 node-fetch到一个错误的 url,我希望它应该被捕获并记录我的适当消息。但是,当我通过节点运行此文件时,它给了我 Uncaught 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.

最佳答案

因为您没有为 catch block 抛出特定错误来捕获。

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);
  });

关于javascript - 捕获 block 在节点提取中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49588215/

相关文章:

reactjs - 功能展示组件中的JS代码

javascript - 在 fetch api 中的 javascript 中重新排列响应

node.js - 将 NodeJS 流消耗到缓冲区并写入流的正确方法

javascript - Node.js从body中获取数据

javascript - 我如何才能通过执行负载中包含的操作来对 APNS 推送消息采取行动

javascript - Angularjs 下拉列表选择值

javascript - 在草案 js 中实现表格支持

javascript - 类方法的可读性作为回调 : with . 绑定(bind)或包装在箭头函数中?

javascript - 无法从 Nodejs 中的 API URL 获取图像文件

javascript - Node js Mongodb findOne 不同步工作