How to catch errors in external js scripts when using puppeteer to introduce them

const runScript = async (filePath, url) => {
 const browser = await puppeteer.launch()
 const page = await browser.newPage()
 await page.goto(url || "http://localhost:9999/index.html", {
   waitUntil: "networkidle2"
 })
 page.on("console", msg => {
   console.log("PAGE:", msg.text())
 })
 // get script path
 let scriptPath = ""
 if (filePath.indexOf("http://") === 0 || filePath.indexOf("https://") === 0) {
   scriptPath = filePath
 } else {
   scriptPath = path.join(filePath)
 }
 let content = fs.readFileSync(scriptPath, {
   encoding: "utf-8"
 })
 console.log(`scriptPath: ${scriptPath}`)
 console.log("------------- script content --------------")
 console.log(content)
 console.log("-------------------------------------------")
 let addRes = await page.addScriptTag({
   // url: "http://localhost:9999/js/hello.js"
  //  path: scriptPath
   content: content
 })
 await addRes.dispose()
 await browser.close()
}

the content of the script I want to test is that there is an error in the script, but = I don"t know how to catch this error when puppeteer is introduced.

let arr = [1, 2, 3]
console.log(arr[3])
let fakeJson = "{"a":123, b: 1}"
let json = JSON.parse(fakeJson)
console.log(json)

current running results

scriptPath: script/error.js
------------- script content --------------
let arr = [1, 2, 3]

console.log(arr[3])

let fakeJson = "{"a":123, b: 1}"

let json = JSON.parse(fakeJson)
console.log(json)
-------------------------------------------
PAGE: 
Jun.23,2021

listens to console events and only records the use of console printing in js.
if you want to record other errors on the page, such as script execution errors or resource loading errors, you also need to listen to other events:
`
/ / record page errors
page.on ('pageerror', msg = > {
console.error (' PAGEERROR', msg)
})
/ / record request failed
page.on ('requestfailed', req = > {
console.log (' Request failed', req)
})
`

)
Menu