I've been studying a lot on asynchronous javascript, from callbacks to promises to async/await.
Now I'm having a hard time understanding why do I lose control over error handling in the following code sample. I've even dived into Node's source code, but that gave me more trouble than answers.
This is what I do:
- Inside a global try/catch block, I call Node's built-in fs.readFile, giving it a callback that just throws an error;
- The error isn't caught, however, and I suppose it somehow bubbles up to the global scope, provoking the JS Engine to emit an uncaughtException event.
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('successfully read file') 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 }
When run, it gives me the following result:
successfully read file
uncaughtExceptionMonitor handler: { ERROR: Error: THROWN BY BUILT-IN FUNCTION'S CALLBACK ORIGIN: uncaughtException }
C:\Users\Heavy\Documents\dev\hwoarang\leg.js:15 throw new Error(
THROWN BY BUILT-IN FUNCTION'S CALLBACK) //error thrown ^Error: THROWN BY BUILT-IN FUNCTION'S CALLBACK at C:\Users\Heavy\Documents\dev\hwoarang\leg.js:15:11 at FSReqCallback.readFileAfterClose [as oncomplete] (node:internal/fs/read_file_context:68:3)
This is my first question so I'm not quite comfortable with Stackoverflow's formatting. I apologize for that.
Can you help me?