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

问题描述 投票:0回答:5

正在努力学习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.
javascript ecmascript-6 node-fetch
5个回答
15
投票

因为你没有抛出特定的错误供 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);
  });


10
投票

就是这部分没被抓住:

 response.json()

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

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

或者简单地返回它,以便它被其他处理程序捕获:

 return response.json()

2
投票

正确的解决方案是首先检查响应状态代码是否为 2xx,因为超出此范围的 HTTP 响应代码不会被视为 JavaScript 错误(因此不会被抛出)。

因此,在开始任何解析之前,您必须检查响应对象上的

ok
属性。

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

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


0
投票

您可以像下面的代码一样使用 catch 处理获取错误

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


0
投票
reject(await response.text())

如果您确定它返回 JSON ,那么

reject(await response.json())
© www.soinside.com 2019 - 2024. All rights reserved.