Skip to content

How to Handle API Errors in Express.js Like a Pro

Himanshu Bansal edited this page Feb 23, 2025 · 2 revisions

Effective error handling in Express.js is crucial for building robust applications. The http-error-kit package offers a structured approach to managing HTTP errors, including the ability to set a global error formatter for consistent error responses.


🚨 The Problem: Inconsistent Error Handling

Developers often handle errors in an ad-hoc manner, leading to:

  • Manual Status Codes: Manually setting status codes can introduce errors.
  • Inconsistent Responses: Different routes may return errors in varying formats.
  • Lack of Metadata: Essential debugging information might be missing.

βœ… The Solution: http-error-kit with Global Formatter

http-error-kit provides predefined HTTP error classes and allows for a global error formatter to standardize error responses across your application.

πŸ“Œ Installing http-error-kit

npm install http-error-kit

πŸ”₯ Implementing Global Error Formatting

  1. Set Up the Global Formatter: Define a formatter function that specifies the structure of your error responses.
  2. Configure the Formatter: Apply this formatter globally using KitHttpErrorConfig.
  3. Use Predefined Error Classes: Replace manual error handling with http-error-kit's error classes.
  4. Centralized Error Handling Middleware: Ensure all errors are processed through a single middleware.

Here's how you can implement this:

const express = require('express');
const { NotFoundError, KitHttpErrorConfig } = require('http-error-kit');
const app = express();

// Define a global formatter
KitHttpErrorConfig.configureFormatter((statusCode, message, details) => ({
  status: statusCode,
  error: message,
  info: details,
  timestamp: new Date().toISOString(),
}));

// Sample route
app.get('/example', (req, res, next) => {
  try {
    // Simulate an error
    throw new NotFoundError('Resource not found', { resource: 'example' });
  } catch (error) {
    next(error);
  }
});

// Centralized Error Response Middleware (Minimal & Correct)
app.use((err, req, res, next) => {
  res.status(err.status || err.statusCode || 500).json(err);
});

app.listen(3000, () => console.log('Server running on port 3000'));

πŸ” Understanding the Implementation

  • Global Formatter: By configuring a global formatter, all instances of KitHttpError will adhere to the defined structure, ensuring consistency.
  • Minimal Centralized Error Handling Middleware: Since errors are already formatted by http-error-kit, we simply return the error instance. No extra processing is needed.

πŸ“’ Benefits of Using http-error-kit

  • Consistency: Uniform error responses across all routes.
  • Customization: Easily adjust the global formatter to include additional fields like timestamps or trace IDs.
  • Simplicity: Reduces boilerplate code by utilizing predefined error classes.

πŸ”₯ Upgrade Your Error Handling Today!

Incorporate http-error-kit into your Express.js applications to achieve efficient, consistent, and scalable error handling.

πŸ‘‰ Explore http-error-kit on npm