Error Handling in Node.js
Error handling is an important part of Node.js development. It helps developers identify errors, handle unexpected situations, prevent application crashes, and return meaningful responses to users. In this tutorial, we will learn different types of errors and how to handle them using practical JavaScript and Express.js examples.
1. What Is Error Handling?
Error handling is the process of detecting, managing, and responding to errors that occur while a program is running.
For example, an application may fail because a file does not exist, a database connection fails, an API request times out, or a user provides invalid input.
Instead of allowing unexpected failures to produce confusing results, we handle errors and return an appropriate response.
try {
const result = 10 / 0;
if (!Number.isFinite(result)) {
throw new Error("The result is not a finite number.");
}
console.log(result);
} catch (error) {
console.log("Error:", error.message);
}
Output
Error: The result is not a finite number.
In this example, throw creates an error, and
catch handles it. JavaScript normally evaluates
10 / 0 as Infinity, so the example explicitly
checks the result and throws an error.
2. Why Is Error Handling Important?
- Prevents unexpected failures from being handled poorly.
- Helps developers identify and troubleshoot problems.
- Provides meaningful error messages to users.
- Protects sensitive technical details from being exposed.
- Helps APIs return appropriate HTTP status codes.
- Improves application reliability and maintainability.
- Makes debugging and production monitoring easier.
3. Types of Errors in Node.js
| Error Type | Description | Example |
|---|---|---|
| Syntax Error | Occurs when JavaScript syntax is invalid. | Missing a closing bracket. |
| Reference Error | Occurs when a variable or identifier cannot be resolved. | Accessing an undeclared variable. |
| Type Error | Occurs when an operation is invalid for a value's type. | Calling a non-function as a function. |
| Runtime Error | An error that occurs while the program is executing. | Reading a missing file. |
| Operational Error | An expected failure caused by an external or application condition. | Database unavailable or invalid input. |
| Programmer Error | A defect in the program's logic or implementation. | Using an incorrect variable or invalid assumption. |
The categories can overlap. For example, a missing file produces a runtime error and may also be an operational error that the application can handle.
4. Handling Errors Using try-catch
The try block contains code that may throw an error.
If an error is thrown, JavaScript transfers control to the
catch block.
try {
console.log("Program started");
throw new Error("Something went wrong");
console.log("This line will not execute");
} catch (error) {
console.log("Error caught:", error.message);
}
console.log("Program continues");
Output
Program started
Error caught: Something went wrong
Program continues
How It Works
- The program enters the
tryblock. - The
throwstatement creates an error. - The remaining statements in that
tryblock are skipped. - The
catchblock receives the error. - After the catch block finishes, execution continues.
try-catch does not
automatically catch errors thrown later by an unrelated asynchronous
callback. Asynchronous operations need the appropriate error-handling
mechanism.
5. Understanding the JavaScript Error Object
JavaScript errors provide useful information about what went wrong. You can inspect the message and stack trace while debugging.
try {
throw new Error("Unable to process the request");
} catch (error) {
console.log("Name:", error.name);
console.log("Message:", error.message);
console.log("Stack:", error.stack);
}
Expected Output (Illustrative)
Name: Error
Message: Unable to process the request
Stack: Error: Unable to process the request
at ...
The exact stack trace depends on the file name, line number, and execution environment.
| Property | Purpose |
|---|---|
error.name |
Identifies the error type. |
error.message |
Describes the error. |
error.stack |
Provides debugging information about the call stack. |
6. Creating Custom Errors
Sometimes the standard Error object is not descriptive enough. A custom error class lets you represent application-specific failures.
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}
function registerUser(email) {
if (!email) {
throw new ValidationError("Email is required");
}
return "User registered successfully";
}
try {
console.log(registerUser(""));
} catch (error) {
if (error instanceof ValidationError) {
console.log("Validation failed:", error.message);
} else {
console.log("Unexpected error:", error.message);
}
}
Output
Validation failed: Email is required
Here, ValidationError represents an invalid registration
input. The application can handle this differently from an unexpected
database or programming error.
7. Error Handling with async/await
Node.js applications frequently use asynchronous operations such as
database queries, file access, and API requests. When an awaited
Promise rejects, a surrounding try-catch can handle it.
function fetchUser() {
return new Promise((resolve, reject) => {
reject(new Error("Unable to fetch user"));
});
}
async function getUser() {
try {
const user = await fetchUser();
console.log(user);
} catch (error) {
console.log("Request failed:", error.message);
}
}
getUser();
Output
Request failed: Unable to fetch user
Explanation
fetchUser()returns a Promise.- The Promise rejects with an Error object.
awaitmakes the rejection throw inside the async function.- The
catchblock handles the rejection.
try-catch must surround the
awaited operation, or the Promise rejection must be handled using
another appropriate mechanism.
8. Error Handling with Promise.catch()
When using Promises directly, the .catch() method handles
a rejection that has not already been handled in the chain.
Promise.reject(new Error("Database connection failed"))
.then((result) => {
console.log(result);
})
.catch((error) => {
console.log("Error:", error.message);
});
Output
Error: Database connection failed
Use .catch() when working with Promise chains. If you
rethrow an error or return another rejected Promise inside
.catch(), that failure must also be handled by a later
handler or the caller.
9. Error Handling with Callbacks
Many Node.js callback APIs use the error-first callback pattern. The first argument represents an error, and the second represents the successful result.
const fs = require("fs");
fs.readFile("missing.txt", "utf8", (error, data) => {
if (error) {
console.log("Unable to read file:", error.code);
return;
}
console.log(data);
});
Possible Output
Unable to read file: ENOENT
ENOENT commonly means the requested file or directory
does not exist. The exact error code depends on the failure.
try-catch generally cannot catch an error reported later
through a callback. Check the callback's error argument instead.
10. Error Handling in Express.js
Express applications commonly use error-handling middleware to handle errors from routes in one central location.
An Express error-handling middleware has four parameters:
err, req, res, and
next.
const express = require("express");
const app = express();
app.use(express.json());
app.get("/api/users", (req, res, next) => {
try {
throw new Error("Unable to retrieve users");
} catch (error) {
next(error);
}
});
// Error-handling middleware must be registered after routes.
app.use((err, req, res, next) => {
console.error(err);
if (res.headersSent) {
return next(err);
}
res.status(500).json({
message: "An internal server error occurred."
});
});
app.listen(3000, () => {
console.log("Server running on port 3000");
});
Test the API
GET http://localhost:3000/api/users
Expected Response
{
"message": "An internal server error occurred."
}
The detailed error is logged on the server, while the client receives a generic response. This prevents internal implementation details from being unnecessarily exposed.
11. Handling Asynchronous Express Errors
Asynchronous route errors must reach Express's error-handling middleware. In Express 5, rejected Promises returned by route handlers are forwarded automatically. In Express 4, asynchronous failures generally need to be forwarded explicitly.
Example for Express 5
app.get("/api/data", async (req, res) => {
const data = await loadData();
res.json(data);
});
If loadData() rejects, Express 5 forwards the error to
error-handling middleware. This example assumes loadData()
is an asynchronous function that returns a Promise.
Compatible Explicit Handling Pattern
app.get("/api/data", async (req, res, next) => {
try {
const data = await loadData();
res.json(data);
} catch (error) {
next(error);
}
});
The explicit pattern works across Express versions and makes the error forwarding visible in the code.
12. Common HTTP Status Codes for Errors
APIs should use status codes that accurately describe the result of the request.
| Status Code | Meaning | Typical Use |
|---|---|---|
| 400 | Bad Request | Invalid input or malformed request. |
| 401 | Unauthorized | Missing or invalid authentication. |
| 403 | Forbidden | Authenticated user lacks permission. |
| 404 | Not Found | Requested resource does not exist. |
| 409 | Conflict | Request conflicts with current resource state. |
| 500 | Internal Server Error | Unexpected server-side failure. |
| 503 | Service Unavailable | Service temporarily cannot handle requests. |
13. Error Handling Flow
The application performs an operation.
Check whether the operation succeeded.
Continue processing and return the result.
Catch or forward the error to a handler.
Return a safe response and record useful diagnostic details.
14. Error Handling Best Practices
- Use
try-catchfor synchronous code that may throw. - Handle rejected Promises using
awaitwithtry-catchor.catch(). - Check the error argument in error-first callbacks.
- Use centralized error-handling middleware in Express applications.
- Return appropriate HTTP status codes.
- Do not expose stack traces, passwords, tokens, or database credentials to clients.
- Log useful diagnostic information without logging secrets.
- Validate user input before performing sensitive operations.
- Do not silently ignore unexpected errors.
- Use monitoring and graceful shutdown strategies for production applications.
Important Points to Remember
- Error handling detects and manages application failures.
try-catchhandles synchronous exceptions.async/awaitworks with Promise rejections..catch()handles rejected Promises.- Callback APIs often report errors through the first argument.
- Custom error classes represent application-specific failures.
- Express error middleware uses four parameters.
- Express 5 forwards rejected route-handler Promises automatically.
- Client responses should not expose internal stack traces.
Summary
Error handling is essential for building reliable Node.js applications. By using try-catch, Promise rejection handlers, error-first callbacks, custom errors, and Express error middleware, developers can handle failures more safely and provide consistent API responses. Proper logging and production monitoring also help identify and resolve problems.