Skip to content
← Back to all articles
For Developers

How to Handle Errors in Node.js Express APIs: A Practical Production Guide

Introduction

A backend API may work correctly during local development and still fail unexpectedly in production.

Network failures, malformed requests, database timeouts and unhandled exceptions can all disrupt the user experience.

A reliable Node.js API should distinguish expected application errors from unexpected failures, return appropriate HTTP status codes, log useful diagnostic information and avoid exposing sensitive implementation details.

This guide demonstrates a practical error-handling approach using Express.

Why centralized error handling matters

Without a consistent error-handling strategy, every route may return a different response format.

One endpoint might return a plain string, another might return an HTML error page, and another might expose an internal stack trace.

Centralized error middleware helps standardize responses and reduces repeated error-handling code.

Create a reusable application error

Start with a custom error class for expected application failures.

class AppError extends Error {
  constructor(message, statusCode = 500) {
    super(message);
    this.name = "AppError";
    this.statusCode = statusCode;
  }
}

This allows the application to represent errors such as invalid input or missing resources using appropriate HTTP status codes.

Handle asynchronous route failures

In Express 5, rejected promises from asynchronous route handlers are automatically forwarded to the error-handling middleware.

For example:

app.get("/api/products/:id", async (req, res) => {
  const product = await getProductById(req.params.id);

  if (!product) {
    throw new AppError("Product not found", 404);
  }

  res.json(product);
});

In Express 4, asynchronous errors generally require explicit forwarding through next(error) or a compatible wrapper.

Add centralized error middleware

Express identifies error middleware through its four-argument signature.

app.use((err, req, res, next) => {
  if (res.headersSent) {
    return next(err);
  }

  console.error({
    message: err.message,
    path: req.path,
    method: req.method
  });

  const statusCode =
    err instanceof AppError ? err.statusCode : 500;

  res.status(statusCode).json({
    success: false,
    message:
      statusCode === 500
        ? "Internal server error"
        : err.message
  });
});

Place this middleware after the application routes.

For unexpected failures, clients receive a generic message while the server retains useful diagnostic information. In production, use structured logging with appropriate redaction rather than indiscriminately recording sensitive request data.

Validate requests before processing

Consider an API endpoint that creates a user account.

If the request body is missing required fields, the application should reject it before attempting a database operation.

app.post("/api/users", async (req, res) => {
  const { email } = req.body ?? {};

  if (
    typeof email !== "string" ||
    !email.trim()
  ) {
    throw new AppError("Valid email is required", 400);
  }

  const user = await createUser(email);

  res.status(201).json(user);
});

This demonstrates a basic presence and type check. A production implementation should also validate email format, enforce length limits, normalize inputs appropriately and use a schema validation library where useful.

Handle database and external API failures

Database queries and external HTTP requests can fail because of timeouts, unavailable services or transient network issues.

A robust application should define appropriate timeouts and translate failures into meaningful responses.

For example, when a required upstream service is unavailable, an API may return HTTP 503 rather than exposing a low-level connection error.

Avoid retrying non-idempotent operations blindly, because doing so can cause duplicate writes or payments.

Test your error-handling behavior

Useful regression scenarios include invalid request payloads, missing resources, rejected database operations, unavailable upstream APIs and unexpected exceptions.

Verify that the application returns the expected status code and JSON structure, logs sufficient diagnostic context and never exposes credentials or stack traces to clients.

Frequently asked questions

What is Express error-handling middleware?

It is middleware with the signature (err, req, res, next) that handles errors passed through the Express middleware chain.

Does Express automatically catch async errors?

Express 5 forwards rejected promises from route handlers automatically. Express 4 typically needs explicit error forwarding or a wrapper.

Should every API error return status 500?

No. Use appropriate status codes such as 400 for invalid requests, 404 for missing resources and 500 for unexpected server failures.

Should production APIs expose stack traces?

Generally, no. Stack traces and internal implementation details should remain in appropriately protected diagnostic logs.

Conclusion

Reliable API error handling is about more than adding a try/catch block.

Centralized middleware, consistent responses, validation, safe logging and automated tests make Node.js services easier to operate and troubleshoot.

Teams that establish these practices early can reduce avoidable debugging effort and provide more predictable experiences for their users.

Need help with Node.js, API debugging or AI integration?

Tekody provides remote engineering and AI development support for developers, startups and software teams. Share your technical requirement and start a conversation.

👉 Request Support: https://tekody.com/get-support/

📲 WhatsApp for Support: +91-8527854783

Suggested internal links: Remote Developer Support, Node.js Development Support, AI Development Services and Contact Tekody

Need help with a similar challenge?

Discuss your requirements with Tekody and explore practical support options.