试图学习,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.
4条答案
按热度按时间u5i3ibmn1#
因为您没有引发catch块要捕捉的特定错误。
kadbb4592#
这是未捕捉的部分:
因此,请将catch行程常式附加到它:
或者简单地将其返回以便由其他处理程序捕获:
rt4zxlrg3#
您可以使用catch处理获取错误,如下所示
mrphzbgm4#
正确的解决方案是首先检查响应状态代码是否为2xx,因为超出此范围的HTTP响应代码不会被视为JavaScript错误(因此不会被抛出)。
因此,在开始任何解析之前,必须检查response对象的
ok
属性。参考:https://dev.to/anchobies/when-that-s-not-so-fetch-error-handling-with-fetch-4cce