我在javascript中解析一个JSON文件。每隔5分钟,JSON会自动使用新数据进行更新,在更新期间JSON为空(大约2秒钟)。
我收到这个错误
未捕获(在promise中)SyntaxError:fetch.then.res中JSON输入的意外结束
这是用于解析JSON的javascript代码:
fetch("http://location/file/data.json")
.then(res => res.json())
.then(data => {
//do something
})
如何控制它,以便它不会标记此错误?我仍然希望使用console.log(Error())
显示客户错误。
任何帮助表示赞赏。
这应该可以解决问题。 then()
将第二个回调函数作为接收错误对象的参数。
fetch("http://location/file/data.json")
.then(res => res.json(), err => console.log(err))
.then(data => {
//do something
}, err => console.log(err))
编辑:根据评论,这种方式是首选。可以在这个link中阅读更多关于使用promises的内容
fetch("http://location/file/data.json")
.then(res => res.json())
.then(data => {
//do something
})
.catch(err => console.log(err)
您可以将.catch
添加到您的处理中:
fetch("http://location/file/data.json")
.then(res => res.json())
.then(data => {
// do something
})
.catch(err => console.log(err.message))
编辑:err.message
而不是JSON.stringify(err)
。