Skip to Content

Error Handling

The REST API Template uses a centralized error handler to ensure consistent and clean JSON responses across all endpoints.


Middleware Location

src/middleware/error.middleware.js

Example

// src/middleware/error.middleware.js export default function errorHandler(err, req, res, next) { res.status(err.status || 500).json({ success: false, message: err.message || "Internal Server Error" }) }

Usage

Registered at the bottom of src/app.js, after all route definitions:

import errorHandler from "./middleware/error.middleware.js" app.use(errorHandler)

This ensures that all thrown or forwarded errors from controllers or services are caught and formatted before reaching the client.


Notes

  • Combine with the built-in ApiError and CatchAsync utilities for structured error propagation.
  • Never handle errors manually inside routes; let middleware do the work.
  • Keeps responses predictable and easy to debug.

Consistent error handling is key to production-grade APIs — NodeBuilder gives you that by default.

Last updated on