http-res-errors

Simple HTTP error response classes for any framework.

Usage no npm install needed!

<script type="module">
  import httpResErrors from 'https://cdn.skypack.dev/http-res-errors';
</script>

README

NPM Version CI codecov Dependency Status Dev Dependency Status

HTTP Response Errors

Simple HTTP error response classes for any framework.

Table of Contents

Features

  • 🚀 Zero dependencies.
  • 🔎 Detect http errors with instanceof.
  • 🎉 Written in TypeScript.

Installation

npm install http-res-errors --save

Usage

Predefined Errors

http-res-errors includes predefined classes for common HTTP status codes.

import { BadRequest } from 'http-res-errors';

throw new BadRequest(`That doesn't work`);
Status Error
400 BadRequest
401 Unauthorized
403 Forbidden
404 NotFound
405 MethodNotAllowed
406 NotAcceptable
408 RequestTimeout
409 Conflict
410 Gone
412 PreconditionFailed
413 PayloadTooLarge
415 UnsupportedMediaType
418 ImATeaPotSupported
421 Misdirected
422 UnprocessableEntity
500 InternalServerError
501 NotImplemented
502 BadGateway
503 ServiceUnavailable
504 GatewayTime
505 HttpVersionNotSupported

Custom Errors

You can use the base HttpError class to return any status.

import { HttpError } from 'http-res-errors';

throw new HttpError(999, 'Something crazy!');

Middleware

Provide catch and response to HTTP errors with frameworks like ExpressJS.

Note: This works with routes that return a promise, like async functions.

import { catchHttpErrors, UnprocessableEntity } from 'http-res-errors';

app.use(catchHttpErrors);

app.get('/', async (res, req) => {
  if (!res.user) {
    throw new Unauthorized('Nice try');
  }

  // ...
});

Development

npm install
npm run build