You've already handled errors throughout this course — checking err in a callback, wrapping await in try/catch. This lesson pulls those together and covers the one Node-specific consequence of getting it wrong: an unhandled error can bring down the entire server, not just the one request that caused it.
try {
const data = JSON.parse('not valid json')
} catch (err) {
console.error('Failed to parse:', err.message)
}Ordinary try/catch — nothing Node-specific here, this works the same as any other JavaScript.
An error in a callback-style function doesn't throw — it arrives as the callback's first argument, and try/catch around the call does nothing to catch it:
fs.readFile('missing.txt', 'utf8', (err, data) => {
if (err) {
console.error('Read failed:', err.message)
return // stop here — data is undefined
}
console.log(data)
})async function loadConfig() {
try {
const data = await fs.readFile('config.json', 'utf8')
return JSON.parse(data)
} catch (err) {
console.error('Failed to load config:', err.message)
return null
}
}A single Node process is usually handling many requests from many different visitors at once. An error that escapes every try/catch — thrown but never caught — crashes the entire process, which means every visitor currently being served loses their connection, not just the one whose request triggered the error.
const server = http.createServer((req, res) => {
try {
const result = riskyOperation(req)
res.end(result)
} catch (err) {
console.error(err)
res.writeHead(500)
res.end('Internal Server Error')
}
})Wrapping request handling in try/catch like this is what keeps one bad request from taking the whole server down — it turns a process crash into a single failed response.
A gotcha worth watching for
A common real-world gap: a request handler wraps its own logic in try/catch, but calls an async function inside it without awaiting it. If that function later rejects, the rejection happens outside the try block entirely and goes unhandled. Always await an async call you want a surrounding try/catch to actually catch.