HTTP Errors Utility

2.0.1 · active · verified Tue Apr 21

http-errors is a utility library for Node.js environments that simplifies the creation of standardized HTTP error objects, making it easier to integrate consistent error handling into web frameworks like Express, Koa, and Connect. The current stable version, 2.0.1, supports Node.js versions 10 and above and offers both CommonJS and ES module exports. The package maintains a stable release cadence with updates focused on maintenance and minor improvements. It provides a declarative API to generate HTTP errors with appropriate status codes, messages, and optional properties such as `expose` (for client visibility) and `headers`. Key differentiators include its simple factory function (`createError`) and direct constructors for common HTTP status codes (e.g., `createError.NotFound`), abstracting the complexity of managing HTTP-specific error properties.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates creating and handling HTTP errors in an Express application, including authentication-related 401s and 404 Not Found errors, using both the factory function and specific error constructors.

import createError, { NotFound } from 'http-errors';
import express from 'express';

const app = express();

// Middleware to simulate authentication
app.use((req, res, next) => {
  // For demonstration, let's assume a user is NOT logged in by default
  req.user = null; // or { id: 1, name: 'Test User' };
  next();
});

app.get('/', (req, res, next) => {
  res.send('Welcome! Try navigating to /protected or /non-existent');
});

app.get('/protected', (req, res, next) => {
  if (!req.user) {
    // Create a 401 Unauthorized error
    return next(createError(401, 'Please login to view this page.'));
  }
  res.send(`Hello, ${req.user.name}! This is a protected page.`);
});

app.get('/non-existent', (req, res, next) => {
  // Create a 404 Not Found error using a specific constructor
  next(new NotFound('The requested resource does not exist.'));
});

// Catch-all for 404s that haven't been caught by other routes
app.use((req, res, next) => {
  next(new NotFound(`Cannot ${req.method} ${req.originalUrl}`));
});

// Error handling middleware
app.use((err, req, res, next) => {
  res.status(err.status || 500);
  res.json({
    status: err.status,
    message: err.expose ? err.message : 'Internal Server Error'
  });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server listening on port ${PORT}`);
  console.log(`Try: http://localhost:${PORT}/`);
  console.log(`Try: http://localhost:${PORT}/protected`);
  console.log(`Try: http://localhost:${PORT}/non-existent`);
});

view raw JSON →