Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@curveball/http-errors

curveball60.6kMIT1.0.1TypeScript support: included

A standard package for HTTP exceptions

http, framework, nodejs, typescript, curveball

readme

HTTP Errors

This package contains a list of standard HTTP exceptions for Typescript. They can be emitted from a Node.js web application written in for example Koa or Curveball, or they can be re-used in a HTTP client.

This package exists because I often find myself re-writing errors such as:

class NotFound extends Error {
  const httpStatus = 404;
}

Instead of doing this over an over again for every client and server-sideproject, it made more sense to be to create 1 generic package that I can re-use for every project I'm working on.

I had trouble finding something similar on NPM, so I hope this is useful to others.

This package has 0 dependencies and is not a part of any frameworks. Someone could use this package and integrate it into their own frameworks as a middleware.

The hope is that as long as this package is independent, it could be used by library authors to throw generic errors with HTTP error information.

Installation

npm install @curveball/http-errors

Getting started

After installing the NPM package, you can very easily reference all the exceptions contained within:

import { NotFound, Forbidden } from '@curveball/http-errors';

throw new NotFound('Article not found');

This also works fine with plain javascript:

const { NotFound, Forbidden } = require('@curveball/http-errors');
throw new Forbidden('You\'re not allowed to update this article');

The library also ships with a simple utility function to see if any error has HTTP error information:

import { isHttpError } from '@curveball/http-errors';

const myError = new Error('Custom error');
myError.httpStatus = 500;

console.log(isHttpError(myError));

The idea is that as long as libraries follow this pattern, they don't need to depend on this library but they can be used automatically by middlewares.

Built-in Error classes such as NotFound, Unauthorized, all have a title property with the default HTTP error string.

const myError = new MethodNotAllowed('I can\'t believe youi\'ve done this');
console.log(myError.title); // Emits "Method Not Allowed"

It also has a utility function to see if something was a Client or Server error:

import { BadRequest, isServerError, isClientError } from '@curveball/http-errors';

const myError = new BadRequest('I didn\'t understand it');
console.log(isClientError(e)); // true
console.log(isServerError(e)); // false

Lastly, a few HTTP responses require or suggest including extra HTTP headers with more information about the error. For example, the 405 Method Not Allowed response should include an Allow header, and the 503 Service Unavailable should have a Retry-After header. The built-in error classes include support these:

import { MethodNotAllowed, ServiceUnavailable } from '@curveball/http-errors';

try {
  throw new MethodNotAllowed('Not allowed', ['GET', 'PUT']);
} catch (e) {
  console.log(e.allow);
}

try {
  throw new ServiceUnavailable('Not open on sundays', 3600*24);
} catch (e) {
  console.log(e.retryAfter);
}

Lastly, it the package has an interface that makes it easier to work with the application/problem+json format, as defined in RFC9457. The interface has type, title, detail and instance properties, which makes it easier to write a generic interface that emits this JSON error format.

API

export function isHttpError(e: Error): e is HttpError;
export function isHttpProblem(e: Error): e is HttpProblem;
export function isClientError(e: Error): boolean;
export function isServerError(e: Error): boolean;

export interface HttpError extends Error {
  httpStatus: number;
}

export interface HttpProblem extends HttpError {

  type: string | null;
  title: string;
  detail: string | null;
  instance: string | null;

}

export class HttpErrorBase extends Error implements HttpProblem {

  type: string | null = null;
  httpStatus: number = 500;
  title: string = 'Internal Server Error';
  detail: string|null = null;
  instance: string | null = null;

  constructor(detail: string|null = null) { }

}

export class BadRequest extends HttpErrorBase { }

type AuthenticateChallenge = string | string[];

export class Unauthorized extends HttpErrorBase {
  wwwAuthenticate: AuthenticateChallenge;
  constructor(detail: string|null = null, wwwAuthenticate?: AuthenticateChallenge) {}
}

export class PaymentRequired extends HttpErrorBase {}
export class Forbidden extends HttpErrorBase {}
export class NotFound extends HttpErrorBase {}

export class MethodNotAllowed extends HttpErrorBase {
  allow: string[]
  constructor(detail: string|null = null, allow?: string[]) {}
}

export class NotAcceptable extends HttpErrorBase {}

export class ProxyAuthenticationRequired extends HttpErrorBase {
  proxyAuthenticate: AuthenticateChallenge;
  constructor(detail: string|null = null, proxyAuthenticate?: AuthenticateChallenge) {}
}

export class RequestTimeout extends HttpErrorBase {}
export class Conflict extends HttpErrorBase {}
export class Gone extends HttpErrorBase {}
export class LengthRequired extends HttpErrorBase {}
export class PreconditionFailed extends HttpErrorBase {}

export class ContentTooLarge extends HttpErrorBase {
  retryAfter: number | null;
  constructor(detail: string|null = null, retryAfter: number|null = null) {}
}

export class UriTooLong extends HttpErrorBase { }
export class UnsupportedMediaType extends HttpErrorBase {}
export class RangeNotSatisfiable extends HttpErrorBase {}
export class ExpectationFailed extends HttpErrorBase {}
export class MisdirectedRequest extends HttpErrorBase {}
export class UnprocessableContent extends HttpErrorBase {}
export class Locked extends HttpErrorBase {}
export class FailedDependency extends HttpErrorBase {}
export class TooEarly extends HttpErrorBase {}
export class UpgradeRequired extends HttpErrorBase {}
export class PreconditionRequired extends HttpErrorBase {}

export class TooManyRequests extends HttpErrorBase {
  retryAfter: number | null;
  constructor(detail: string|null = null, retryAfter: number|null = null) {}
}

export class RequestHeaderFieldsTooLarge extends HttpErrorBase {}
export class UnavailableForLegalReasons extends HttpErrorBase {}
export class InternalServerError  extends HttpErrorBase {}
export class NotImplemented extends HttpErrorBase {}
export class BadGateway extends HttpErrorBase {}

export class ServiceUnavailable extends HttpErrorBase {
  retryAfter: number | null;
  constructor(detail: string|null = null, retryAfter: number|null = null) {}
}

export class GatewayTimeout extends HttpErrorBase {}
export class HttpVersionNotSupported extends HttpErrorBase {}
export class VariantAlsoNegotiates extends HttpErrorBase {}
export class UnsufficientStorage extends HttpErrorBase {}
export class LoopDetected extends HttpErrorBase {}
export class NetworkAuthenticationRequired extends HttpErrorBase {}

...

changelog

Changelog

1.0.1 (2024-01-20)

  • Remove dependency on @curveball/kernel

1.0.0 (2024-01-15)

  • Finally! Curveball v1. Only took 6 years.
  • CommonJS support has been dropped. The previous version of this library supported both CommonJS and ESM. The effort of this no longer feels worth it. ESM is the future, so we're dropping CommonJS.
  • Now requires Node 18.
  • Upgraded to Typescript 5.3.
  • To match RFC9110, UnprocessableEntity is now UnprocessableContent, and PayloadToolarge is now ContentTooLarge. The old classes still exist and have been marked as deprecated.
  • Updated references from RFC7807 to RFC9457.

0.5.0 (2023-02-14)

  • This package now supports ESM and CommonJS modules.
  • No longer supports Node 14.

0.4.1 (2022-01-15)

  • isHttpError and isHttpProblem can now take any (unknown) type as arguments, making it easier to use these functions without casting.
  • Forbiddden -> Forbidden.
  • Update everything to latest curveball defaults.
  • Update all dependencies.

0.4.0 (2021-02-18)

  • Update everything to latest curveball standards.
  • Publish on github packages

0.3.0 (2018-10-01)

  • Mass-renamed httpCode to the more common httpStatus.
  • Added all missing status codes.
  • Fully unittested.

0.2.2 (2018-09-14)

  • Added isHttpProblem() helper function.
  • Added 408, 409, 410, 411, 412, 413.

0.2.1 (2018-09-14)

  • The allow parameter from MethodNotAllowed is now optional.
  • Added 406, 407, 422.

0.2.0 (2018-09-12)

  • Added Unauthorized, PaymentRequired, Forbidden.
  • Added support for WWW-Authenticate header for 401 responses and Allow for 405 responses.

0.1.0 (2018-09-11)

  • Dropped ClientError and ServerError interfaces, they aren't useful in TS.
  • Added HttpError and HttpProblem interfaces.
  • Added isHttpError type guard.
  • Added isClientError and isServerError helpers.

0.0.1 (2018-09-11)

  • First version with just a few errors to test the ergonomics of this package.