🔍 What is an Error in Node.js?
An error is something that goes wrong in your program. For example:
- A file might not exist.
- A database might not respond.
- A variable might be undefined.
Node.js needs a way to handle these problems so that the program does not crash and can give a meaningful response.
🛠️ Types of Errors in Node.js
Synchronous Errors
- These happen immediately during the execution of code.
- Example: Trying to use a variable that is not defined.
Asynchronous Errors
- These happen later, like when waiting for a file read, database query, or API call.
- Node.js uses callbacks, promises, or async/await to deal with them.
🧰 Handling Errors with try...catch (Synchronous Code)
For code that runs immediately, we use try...catch.
// Using try...catch
try {
let result = JSON.parse("invalid json");
console.log(result);
} catch (error) {
console.error("Something went wrong:", error.message);
}
If JSON parsing fails, the error is caught and handled, so the program doesn’t crash.
🔗 Handling Errors in Callbacks (Asynchronous Code)
In Node.js, many functions use the error-first callback pattern.
// Error-first callback
const fs = require('fs');
fs.readFile('file.txt', 'utf8', (err, data) => {
if (err) {
console.error("Error reading file:", err.message);
return;
}
console.log("File content:", data);
});
The first argument err is used to check if something went wrong.
📦 Handling Errors with Promises
When using Promises, we handle errors with .catch().
// Promise error handling
const fs = require('fs').promises;
fs.readFile('file.txt', 'utf8')
.then(data => console.log("File content:", data))
.catch(err => console.error("Error:", err.message));
If reading the file fails, .catch() will run.
🚀 Handling Errors with Async/Await
Async/await makes code look cleaner. We still use try...catch.
// Async/Await error handling
const fs = require('fs').promises;
async function readFileData() {
try {
const data = await fs.readFile('file.txt', 'utf8');
console.log("File content:", data);
} catch (err) {
console.error("Error:", err.message);
}
}
readFileData();
The try...catch block catches any errors inside async functions.
🌐 Error Handling in Express.js Middleware
In Express.js, special error-handling middleware is used.
// Express.js error handling
const express = require('express');
const app = express();
app.get('/', (req, res) => {
throw new Error("Something broke!");
});
// Error-handling middleware
app.use((err, req, res, next) => {
console.error(err.message);
res.status(500).send("Internal Server Error");
});
app.listen(3000, () => console.log('Server running on http://localhost:3000'));
If something goes wrong, Express sends a proper error response instead of crashing.
📊 Best Practices for Error Handling
- Always handle both synchronous and asynchronous errors.
- Use try...catch for synchronous code and .catch() or async/await for asynchronous code.
- In callbacks, always check the first error argument.
- Use logging tools like Winston or Morgan for better error tracking.
- Do not expose internal errors directly to users. Send friendly messages.
📝 Summary
In Node.js, errors can be synchronous (happen immediately) or asynchronous (happen later). We can handle them using try...catch, callbacks, promises, and async/await. In web apps built with Express.js, error-handling middleware is used. Good error handling makes applications reliable, prevents crashes, and provides meaningful feedback to users.