HTTP Error Response Generator

3.0.1 · active · verified Wed Apr 22

The `error-http-response` package provides a utility to convert JavaScript `Error` objects into standardized HTTP problem detail objects, adhering to RFC 7807. It's currently stable at version 3.0.1, with major releases primarily driven by updates to the minimal supported Node.js version. The library automatically maps standard error properties like `name`, `message`, and `stack` to the generated HTTP response fields, and allows for extensive customization via `error.http` properties or direct options. It supports both Node.js (>=18.18.0) and browser environments, and ships with TypeScript definitions, making it suitable for modern JavaScript and TypeScript projects that need to consistently format API error responses without manual serialization.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates converting a custom error with additional properties into an RFC 7807-compliant HTTP problem details object, overriding some fields.

import errorHttpResponse from 'error-http-response';

class AuthError extends Error {
  constructor(...args) {
    super(...args);
    this.http = {
      type: 'https://example.com/probs/auth',
      status: 401,
    };
    // Ensure stack trace is captured
    Error.captureStackTrace(this, AuthError);
  }
}

const error = new AuthError('Could not authenticate.');
error.userId = 62;
Object.assign(error.http, {
  instance: '/users/62',
  extra: { userId: 62 },
});

const object = errorHttpResponse(error, {
  extra: { isHttp: true },
});

console.log(object);
// Expected output:
// {
//   type: 'https://example.com/probs/auth',
//   status: 401,
//   title: 'AuthError',
//   detail: 'Could not authenticate.',
//   instance: '/users/62',
//   stack: 'AuthError: Could not authenticate.\n    at ...',
//   extra: { isHttp: true, userId: 62 }
// }

view raw JSON →