Node.js › Error Handling
What is the difference between throwing an error synchronously and calling a callback with an error as its first argument in Node.js?
BeginnerAnswer
Synchronous code throws an Error object directly, caught by a surrounding try/catch. Traditional Node.js callback-style asynchronous functions instead follow the 'error-first callback' convention, passing an error (or null if none occurred) as the callback's first argument, since a thrown error inside an async callback executing later couldn't be caught by a try/catch wrapped around the original function call, as that call has already returned by the time the callback runs.
// Synchronous: throw and catch
function parseConfig(json) {
try { return JSON.parse(json); } catch (err) { throw new Error('Invalid config JSON'); }
}
// Asynchronous callback-style: error-first convention
fs.readFile('config.json', (err, data) => {
if (err) return console.error('Failed to read config:', err.message);
console.log(data);
});Real-world example A developer new to Node.js initially wrapped an fs.readFile call in a try/catch expecting to catch a file-not-found error, only to realize the callback-based API requires checking the err parameter inside the callback itself, since the try/catch around the outer call can't catch an error surfaced asynchronously.