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

Rah*_*eel 1 javascript ecmascript-6 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.
Run Code Online (Sandbox Code Playgroud)

小智 11

因为您没有为 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);
  });
Run Code Online (Sandbox Code Playgroud)


Jon*_*lms 5

其未捕获的这部分:

 response.json()
Run Code Online (Sandbox Code Playgroud)

因此,将捕获处理程序附加到它:

 response.json().catch(...)
Run Code Online (Sandbox Code Playgroud)

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

 return response.json()
Run Code Online (Sandbox Code Playgroud)