1.2.1 • Published 3 years ago

@jdpnielsen/http-error v1.2.1

Weekly downloads
6
License
MIT
Repository
github
Last release
3 years ago

Http Error: rich http errors

Build Status Conventional Commits

The Http Error module is an extension of Contextual Error, inspired by Hapi's Boom. The module allows wrapping of errors in a safe way, and delegate the handling to a centralized errorhandler without loosing important context.

Quick start

First, install the package:

npm install @jdpnielsen/http-error

You can use the built in factory functions to wrap downstream errors:

import { notFound } from '@jdpnielsen/http-error';

server.get('/:id', {}, async function getIndex(request, response) {
  let document;

  try {
    document = await fsPromises.readFile(join(__dirname, './index.html'));
  } catch(error) {
    if (error.code === 'ENOENT') {
      throw notFound('Index file not found', { cause: error, publicInfo: { file: './index.html' } })
    } else {
      throw serverError('Something went wrong while reading index file', { cause: error })
    }
  }

  /* ... */
});

if the thrown error is logged the result should be something like:

HttpError [NotFoundError]: Index file not found
    at getIndex (/home/folder/request.js:12:10) {
  info: {},
  shortMessage: 'Index file not found',
  cause: [Error: ENOENT: no such file or directory, open '/home/folder/index.html'] {
    errno: -2,
    code: 'ENOENT',
    syscall: 'open',
    path: '/home/folder/index.html'
  },
  statusCode: 404,
  response: {
    statusCode: 404,
    error: 'Not Found',
    message: 'Index file not found',
    info: { file: './index.html' }
  }
}

Assuming some kind of errorhandler is mounted, which stringifies the error, the http response should be:

{
  "statusCode": 404,
  "error": "Not Found",
  "message": "Index file not found",
  "info": { "file": "./index.html" }
}

Factory function api

type FactoryFunction = (message?: string, { cause?: Error, publicInfo?: Object, info?: Object }) => HttpError;
Param nameTypeMeaning
messagestringError message
causeErrorDownstream error. Will not show up in response
publicInfoobjectInfo which should be included in response.
infoobjectInfo which should be included for debugging. Will not be included in response.

Available factory functions

exportstatusCodemessage
badRequest400Bad Request
unauthorized401Unauthorized
paymentRequired402Payment Required
forbidden403Forbidden
notFound404Not Found
methodNotAllowed405Method Not Allowed
notAcceptable406Not Acceptable
proxyAuthRequired407Proxy Authentication Required
clientTimeout408Request Time-out
conflict409Conflict
resourceGone410Gone
lengthRequired411Length Required
preconditionFailed412Precondition Failed
entityTooLarge413Request Entity Too Large
uriTooLong414Request-URI Too Large
unsupportedMediaType415Unsupported Media Type
rangeNotSatisfiable416Requested Range Not Satisfiable
expectationFailed417Expectation Failed
teapot418I\'m a teapot
badData422Unprocessable Entity
locked423Locked
failedDependency424Failed Dependency
tooEarly425Too Early
preconditionRequired428Precondition Required
tooManyRequests429Too Many Requests
illegal451Unavailable For Legal Reasons
serverError500Internal Server Error
internal500Internal Server Error
notImplemented501Not Implemented
badGateway502Bad Gateway
serverUnavailable503Service Unavailable
gatewayTimeout504Gateway Time-out

Custom HttpErrors

The HttpError Base class is available and can either be extended or used to create new factory functions:

import HttpError from '@jdpnielsen/http-error';
import { Info } from '@jdpnielsen/contextual-error';

export function custom(message?: string, input?: { cause?: Error, info?: Info, publicInfo?: Info }): HttpError {
	return new HttpError(500, 'Custom', message, input?.publicInfo, input?.cause, {
		name: 'customError',
		constructorOpt: custom,
		info: input?.info,
	});
}