err-http

1.2.2 · abandoned · verified Wed Apr 22

The `err-http` package provides a collection of error constructors specifically designed for common HTTP status codes, simplifying error management in web applications. It allows developers to easily create custom error types that inherit from the standard `Error` object and automatically carry an associated HTTP status code, such as `BadRequestError` (400) or a custom `TeapotError` (418). Currently stable at version 1.2.2, the library has not seen significant updates or new major versions since 2014, indicating an abandoned state. Its core value lies in its straightforward approach to mapping application errors to HTTP semantics, enabling clearer API responses. However, its CommonJS-only nature and lack of active maintenance pose challenges for modern JavaScript development practices, particularly within ESM-first projects or those relying on TypeScript for type safety. This package serves as a foundational example of HTTP error handling but is largely superseded by more actively maintained alternatives.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates creating and using pre-defined `err-http` errors (like BadRequestError) and custom errors (like TeapotError) within an Express application, showing how error handling middleware can leverage the `status` property of these errors.

const express = require('express');
const app = express();
const port = 3000;

// Import specific error constructor for 400 Bad Request
const BadRequestError = require('err-http/badrequest');

// Import the factory to create a custom error (e.g., HTTP 418 I'm a Teapot)
const CustomTeapotError = require('err-http')('TeapotError', 'I am a teapot', 418);

app.get('/api/resource', (req, res, next) => {
  // Simulate an invalid request if a required query parameter is missing
  if (!req.query.id) {
    return next(new BadRequestError('Missing required query parameter: id.'));
  }
  res.json({ message: `Resource with ID ${req.query.id} found.` });
});

app.get('/api/coffee', (req, res, next) => {
  // Simulate a custom teapot error for a coffee request
  next(new CustomTeapotError('Sorry, this server is a teapot and cannot brew coffee.'));
});

// Generic error handling middleware
app.use((err, req, res, next) => {
  console.error(err.stack);
  // `err-http` errors have a `status` property
  const status = err.status || 500;
  const message = err.message || 'Internal Server Error';
  res.status(status).json({ error: message, code: status });
});

app.listen(port, () => {
  console.log(`Server listening at http://localhost:${port}`);
  console.log('Test with: http://localhost:3000/api/resource'); // Should return 400
  console.log('Test with: http://localhost:3000/api/resource?id=123'); // Should return 200
  console.log('Test with: http://localhost:3000/api/coffee'); // Should return 418
});

view raw JSON →