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

lh80um4z  于 2022-11-27  发布在  Java
关注(0)|答案(4)|浏览(128)

试图学习,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.
u5i3ibmn

u5i3ibmn1#

因为您没有引发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);
  });
kadbb459

kadbb4592#

这是未捕捉的部分:

response.json()

因此,请将catch行程常式附加到它:

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

或者简单地将其返回以便由其他处理程序捕获:

return response.json()
rt4zxlrg

rt4zxlrg3#

您可以使用catch处理获取错误,如下所示

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

mrphzbgm4#

正确的解决方案是首先检查响应状态代码是否为2xx,因为超出此范围的HTTP响应代码不会被视为JavaScript错误(因此不会被抛出)。
因此,在开始任何解析之前,必须检查response对象的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

相关问题