[英]catch error message from 404 response with axios or fetch in javascript
[英]JavaScript fetch() can't catch error from 404
我正在尝试使用此fetch()函数处理Chrome中的404。
function promiseBatchDomains(domainsToQuery) {
var batchSize = domainsToQuery.length
var currentDomain = 0
var promises = domainsToQuery.map(domain => (
fetch(`https://api-url-omitted/${domain}`)
.then( res => {
if (res.ok) {
return res
} else {
throw Error(res.statusText)
}
})
.then(res => res.json())
.then(res => {
currentDomain += 1
console.log(currentDomain + " of " + batchSize + ': ' + domain + ' data received.')
percentCompletion = parseFloat(currentDomain / batchSize).toLocaleString(undefined,{style: 'percent'})
$('#batchProgressBar').attr('aria-valuenow', percentCompletion).width(percentCompletion)
return res
})
.then(res => ({ domain, res })
.catch(error => console.log("Error: " + error))
))).filter(Boolean)
Promise.all(promises)
.then(results => makeCSV(results))
}
我需要帮助来理解为什么我在if / else语句中引发的错误没有被catch捕获。
基于此处 , 此处 , 此处和此处概述的方法,我尝试了几种不同的方法:通过抛出错误(如我的上面的代码)以及Promise.reject()
。 无论哪种方式都挂断了,所以我想知道是否遗漏了一些更基本的东西。
在我的控制台中,我只看到原始的404,但没有看到我的错误中的console.log,我相信如果触发捕获,该错误就会触发。 (如果不是404,则此功能的其余部分将按预期工作。)
更新:我已经使用如下if语句重构了第三个.then()
方法:
.then(res => {
currentDomain += 1
if (domain) {
console.log(currentDomain + " of " + batchSize + ': ' + domain + ' data received.')
percentCompletion = parseFloat(currentDomain / batchSize).toLocaleString(undefined,{style: 'percent'})
$('#batchProgressBar').attr('aria-valuenow', percentCompletion).width(percentCompletion)
return {domain, res}
}
})
现在捕获触发。 不应该throw Error()
导致它跳过所有.then()
方法并直接进入错误状态吗?
好的,所以这里有几个问题可以解决:
.filter(Boolean)
的下Promise.all()
像这样: Promise.all(promises).then(results => results.filter(Boolean)).then(results => makeCSV(results))
filter(Boolean)不是原始问题中提到的问题的一部分,但最终导致未定义的变量传递给后续函数。 通过以这种方式过滤布尔值,我避免了向下游传递错误的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.