Modern Errors HTTP Response Plugin

5.0.1 · active · verified Wed Apr 22

modern-errors-http is a plugin for the modern-errors library, designed to convert custom error instances into RFC 7807 compliant "problem details" objects suitable for HTTP responses. The current stable version is 5.0.1. Releases typically follow updates to its peer dependency, modern-errors, and align with Node.js LTS versions, indicating a deliberate and stable release cadence. Its key differentiators include seamless integration with the modern-errors ecosystem, adherence to the standardized RFC 7807 format for error responses, and broad compatibility across both Node.js (>=18.18.0) and browser environments. The package also ships with full TypeScript type definitions, enhancing developer experience and compile-time safety for TypeScript users. It simplifies the creation of consistent, machine-readable HTTP error payloads for APIs.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to integrate the modern-errors-http plugin, define custom HTTP errors, and generate RFC 7807 compliant problem detail objects for API responses.

import ModernError from 'modern-errors';
import modernErrorsHttp from 'modern-errors-http';

// 1. Extend ModernError with the HTTP plugin
export const BaseError = ModernError.subclass('BaseError', {
  plugins: [modernErrorsHttp],
});

// 2. Define a custom error with HTTP-specific properties
export const AuthError = BaseError.subclass('AuthError', {
  http: {
    type: 'https://example.com/probs/auth',
    status: 401,
    title: 'Authentication Failed'
  },
});

// 3. Create an instance of the custom error
const error = new AuthError('Could not authenticate the provided credentials.', {
  http: {
    instance: '/users/62/login',
    extra: { userId: 62, attemptedUsername: 'testuser' },
  },
});

// 4. Convert the error to an RFC 7807 compliant HTTP response object
const httpResponseObject = BaseError.httpResponse(error);

// In a real application, this 'httpResponseObject' would be sent as a JSON response body.
console.log(JSON.stringify(httpResponseObject, null, 2));
/*
Expected output (stack trace will vary):
{
  "type": "https://example.com/probs/auth",
  "status": 401,
  "title": "Authentication Failed",
  "detail": "Could not authenticate the provided credentials.",
  "instance": "/users/62/login",
  "stack": "AuthError: Could not authenticate the provided credentials.\n    at ...",
  "extra": {
    "userId": 62,
    "attemptedUsername": "testuser"
  }
}
*/

view raw JSON →