Introduction
Errors are a normal part of application development. A database connection may fail, a user may request a record that does not exist, or an API may receive invalid input. Node.js provides built-in error handling features, but sometimes standard errors do not clearly describe what went wrong in an application.
For example, a generic error such as Error: Something went wrong does not tell us whether a user was not found, the request data was invalid, or access was denied.
Custom errors in Node.js help developers create meaningful error types for specific situations. They make applications easier to debug, maintain, and manage, especially when working with REST APIs, databases, and large applications.
In this tutorial, you will learn how to create custom errors using JavaScript classes, throw and catch them, and use them in real-world Node.js applications.
What Are Custom Errors in Node.js?
Custom errors are user-defined error types created to represent specific problems in an application.
Node.js provides the built-in Error class. By extending this class, developers can create errors such as:
- ValidationError – when input data is invalid.
- NotFoundError – when a requested resource does not exist.
- AuthenticationError – when authentication fails.
- DatabaseError – when a database operation fails.
For example, instead of throwing a general error when a user cannot be found, an application can throw a NotFoundError.
This allows the application to identify the error type and respond appropriately.
Why Use Custom Errors?
Custom errors offer several advantages:
- Clearer error messages: They explain what went wrong.
- Better error handling: Different errors can be handled in different ways.
- Easier debugging: Error types help developers identify the source of a problem.
- Consistent API responses: Applications can return suitable HTTP status codes for different errors.
- Improved maintainability: Error-handling logic becomes easier to understand as an application grows.
For example, a missing user might produce an HTTP 404 Not Found response, while invalid input might produce 400 Bad Request.
How to Create a Custom Error in Node.js
JavaScript allows you to create a custom error class by extending the built-in Error class.
Syntax
class CustomError extends Error {
constructor(message) {
super(message);
this.name = "CustomError";
}
}
Here is what each part means:
- class CustomError defines a new error class.
- extends Error inherits properties and behavior from the built-in Error class.
- super(message) passes the error message to the parent class.
- this.name sets a meaningful name for the error.
Using super() is important because it initializes the standard error message and stack trace.
Example: Creating and Throwing a Custom Error
Let’s create a custom error called ValidationError. We will use it when a user provides an invalid age.
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}
function validateAge(age) {
if (age < 18) {
throw new ValidationError(
"Age must be at least 18."
);
}
return "Age is valid.";
}
try {
console.log(validateAge(16));
} catch (error) {
console.log(error.name);
console.log(error.message);
}
Output:
Age must be at least 18.
Explanation
In this example, ValidationError extends the built-in Error class. The validateAge() function checks whether the supplied age meets the requirement.
When the age is below 18, the function throws a ValidationError. The catch block receives the error and displays its name and message.
If you call validateAge(21), the function returns Age is valid. instead.
Creating Custom Errors with Additional Properties
Sometimes, an error needs more information than a message. For example, a REST API may need to associate an error with an HTTP status code.
You can add custom properties to your error class.
class AppError extends Error {
constructor(message, statusCode) {
super(message);
this.name = "AppError";
this.statusCode = statusCode;
this.isOperational = true;
}
}
const error = new AppError(
"User not found.",
404
);
console.log(error.name);
console.log(error.message);
console.log(error.statusCode);
Output:
User not found.
404
In this example:
- message describes the problem.
- statusCode stores the relevant HTTP status code.
- isOperational can be used by an application's error-handling logic to identify expected application errors.
The isOperational property is a convention, not a built-in Node.js feature. Applications should define clearly how they use it.
Creating Specific Custom Error Classes
An application can have multiple error types that extend a shared base error class. This avoids repeating common properties and makes errors easier to distinguish.
class AppError extends Error {
constructor(message, statusCode) {
super(message);
this.name = this.constructor.name;
this.statusCode = statusCode;
}
}
class NotFoundError extends AppError {
constructor(message = "Resource not found.") {
super(message, 404);
}
}
class ValidationError extends AppError {
constructor(message = "Invalid input.") {
super(message, 400);
}
}
try {
throw new NotFoundError("User not found.");
} catch (error) {
if (error instanceof NotFoundError) {
console.log("Not Found:", error.message);
console.log("Status Code:", error.statusCode);
} else {
console.log("Unexpected error:", error.message);
}
}
Output:
Status Code: 404
The NotFoundError class inherits the common functionality from AppError and sets the status code to 404. Similarly, ValidationError uses status code 400.
The instanceof operator checks whether an error belongs to a particular class or inherits from it. This is useful when an application needs different handling for different error types.
Real-Life Example: Custom Errors in a Node.js API
Consider a Node.js application that retrieves user information. If a requested user does not exist, the application should return a suitable error instead of a successful response.
The following example uses Express and demonstrates how a custom error can be passed to centralized error-handling middleware.
Install Express if it is not already installed:
npm install express
Create an app.js file:
const express = require("express");
const app = express();
app.use(express.json());
class AppError extends Error {
constructor(message, statusCode) {
super(message);
this.name = this.constructor.name;
this.statusCode = statusCode;
}
}
class NotFoundError extends AppError {
constructor(message = "Resource not found.") {
super(message, 404);
}
}
const users = [
{ id: 1, name: "Amit" },
{ id: 2, name: "Priya" }
];
app.get("/users/:id", (req, res, next) => {
const userId = Number(req.params.id);
const user = users.find(
(item) => item.id === userId
);
if (!user) {
return next(
new NotFoundError("User not found.")
);
}
res.json(user);
});
// Centralized error-handling middleware
app.use((err, req, res, next) => {
const statusCode = err.statusCode || 500;
res.status(statusCode).json({
success: false,
message: statusCode === 500
? "Internal server error."
: err.message
});
});
app.listen(3000, () => {
console.log("Server running on port 3000");
});
Run the application:
node app.js
Open the following URL in your browser or API testing tool:
http://localhost:3000/users/1
The response will contain the user:
{
"id": 1,
"name": "Amit"
}
Now request a user that does not exist:
http://localhost:3000/users/10
The API will return a 404 response:
{
"success": false,
"message": "User not found."
}
How This Example Works
The application searches for a user based on the ID provided in the URL. If the user exists, it returns the user information.
If the user does not exist, the route creates a NotFoundError and passes it to next(). Express forwards the error to the centralized error-handling middleware, which returns the appropriate HTTP response.
This approach keeps route handlers cleaner and avoids repeating the same error-response logic throughout the application.
The example uses in-memory data for simplicity. A production application would typically retrieve the user from a database.
Handling Custom Errors with Async/Await
Custom errors are also useful when working with asynchronous operations, such as database queries and file access.
Consider the following example:
class NotFoundError extends Error {
constructor(message) {
super(message);
this.name = "NotFoundError";
}
}
async function getUser(id) {
const user = null; // Simulating a missing user
if (!user) {
throw new NotFoundError(
`User with ID ${id} was not found.`
);
}
return user;
}
async function main() {
try {
const user = await getUser(10);
console.log(user);
} catch (error) {
if (error instanceof NotFoundError) {
console.log(error.message);
} else {
console.error("Unexpected error:", error);
}
}
}
main();
Output:
When an error is thrown inside an async function, the function's returned Promise is rejected. The await expression inside the try block allows the catch block to handle that rejection.
In real applications, make sure asynchronous errors are handled at an appropriate level. For Express 4, rejected Promises in asynchronous route handlers generally need to be forwarded to next(error) explicitly or through a wrapper. Express 5 automatically forwards rejected route-handler Promises to error-handling middleware.
Common Mistakes When Using Custom Errors
1. Not Extending the Error Class
Creating a regular class without extending Error means you may lose standard error behavior, such as a useful stack trace.
Recommended approach:
class DatabaseError extends Error {
constructor(message) {
super(message);
this.name = "DatabaseError";
}
}
2. Forgetting to Call super()
When a class extends another class, its constructor must call super() before accessing this.
Without it, JavaScript throws an error while constructing the object.
3. Ignoring Asynchronous Errors
A try...catch block cannot catch a rejected Promise that is started but neither awaited nor otherwise handled.
Incorrect:
try {
getUser(10);
} catch (error) {
console.log(error.message);
}
Correct:
try {
await getUser(10);
} catch (error) {
console.log(error.message);
}
The corrected example must be inside an async function or another valid context that supports await.
4. Returning Internal Error Details to Clients
Database errors, stack traces, file paths, and internal configuration details should not be exposed in production API responses.
Return a safe, meaningful message to clients and log the detailed error securely on the server.
5. Treating Every Error as a Client Error
Not every error should return a 400 or 404 status code. Unexpected programming errors and server failures usually require a 500 Internal Server Error response.
Choose status codes based on the actual problem.
Best Practices for Custom Errors in Node.js
- Extend the built-in Error class when creating custom error types.
- Use descriptive class names such as ValidationError and NotFoundError.
- Add properties such as statusCode only when they serve a clear purpose.
- Use centralized error-handling middleware in Express applications.
- Handle rejected Promises correctly when using asynchronous functions.
- Avoid exposing sensitive error details to clients.
- Log unexpected errors so developers can investigate them.
- Do not silently ignore errors or return success responses when an operation fails.
Conclusion
Custom errors in Node.js help developers handle application problems in a clear and consistent way. By extending the built-in Error class, you can create meaningful error types, attach additional information, and distinguish between different failures.
They are especially useful in REST APIs, database-driven applications, and asynchronous operations. When combined with proper try...catch blocks and centralized error-handling middleware, custom errors make Node.js applications easier to debug, maintain, and scale.