我们可以明确且具体地捕获 Puppeteer (Chrome/Chromium) 错误吗
net::ERR_ABORTED
?或者字符串匹配是目前唯一的选择?
page.goto(oneClickAuthPage).catch(e => {
if (e.message.includes('net::ERR_ABORTED')) {}
})
/* "net::ERROR_ABORTED" occurs for sub-resources on a page if we navigate
* away too quickly. I'm specifically awaiting a 302 response for successful
* login and then immediately navigating to the auth-protected page.
*/
await page.waitForResponse(res => res.url() === href && res.status() === 302)
page.goto(originalRequestPage)
理想情况下,这类似于我们可以用
page.on('requestaborted')
捕获的潜在事件
由于没有其他人直接回答您的问题,字符串匹配似乎仍然是唯一的选择。
这是我在特别容易出现 ERR_ABORTED 错误的区域使用的一些示例代码:
try {
await page.goto(oneClickAuthPage)
} catch (err) {
if (err.message.startsWith('net::ERR_ABORTED')) {
console.log("Caught ERR_ABORTED")
// handle the error however you want
}
else {
throw err
}
}
这是我最初得到这个解决方案的地方,减去我编辑以匹配您的问题的部分。
我建议将您的 api 调用等放在 trycatch 块中 如果失败,您会捕获错误,就像您当前所做的那样。但只是看起来好看一点而已
try {
await page.goto(PAGE)
} catch(error) {
console.log(error) or console.error(error)
//do specific functionality based on error codes
if(error.status === 300) {
//I don't know what app you are building this in
//But if it's in React, here you could do
//setState to display error messages and so forth
setError('Action aborted')
//if it's in an express app, you can respond with your own data
res.send({error: 'Action aborted'})
}
}
如果 Puppeteer 中止时的错误响应中没有特定的错误代码,则意味着 Puppeteer 的 API 尚未编码为返回这样的数据,不幸的是:')
像您在问题中所做的那样进行错误消息检查并不少见。不幸的是,这是我们能做到的唯一方法,因为这就是我们的工作方式:'P