我一直在研究异步javascript,从回调到promise ,再到异步/等待.
现在我很难理解为什么在下面的代码示例中我会失go 对错误处理的控制.我甚至深入研究了Node的源代码,但这给了我更多的麻烦,而不是答案.
我就是这么做的:
- 在全局try/catch块中,我调用 node 的内置fs.readFile,给它一个callback that just throws an error;
- 然而,错误没有被捕获,我想它以某种方式冒泡到全局范围,激发JS引擎发出uncaughtException事件.
const { readFile } = require('node:fs') process.on('uncaughtExceptionMonitor', (error, origin) => { console.log('\nuncaughtExceptionMonitor handler: {') console.log(`ERROR: ${error}`) console.log(`ORIGIN: ${origin}`) console.log('}\n') }) try { readFile('./jsconfig.json', 'utf8', (err, res) => { if (err) console.log('failed to read file') if (res) console.log('已成功读取文件') throw new Error(`THROWN BY BUILT-IN FUNCTION'S CALLBACK`) //error thrown }) } catch (error) { console.log(`error caught by readFile's outer scope`) // not caught here }
运行时,它会给出以下结果:
已成功读取文件
uncaughtExceptionMonitor处理程序:{错误:错误:由内置
C: \Users\Heavy\Documents\dev\hwarang\leg.js:15
错误:由内置函数的回调引发
这是我的第一个问题,所以我对Stackoverflow的格式不太熟悉.我为此道歉.
你能帮助我吗?