@curveball/http-errors0.3.0 • Public • Published
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:
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.
npm install @curveball/http-errors
After installing the NPM package, you can very easily reference all the exceptions contained within:
;throw new NotFound'Article not found';
const NotFound Forbidden = ;throw '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:
;;myError.httpStatus = 500;console.logisHttpErrormyError;
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
Unauthorized, all have a
property with the default HTTP error string.
;console.logmyError.title; // Emits "Method Not Allowed"
It also has a utility function to see if something was a Client or Server error:
;;console.logisClientErrore; // trueconsole.logisServerErrore; // false
Lastly, a few HTTP errors require or suggest including extra HTTP headers with
more information about headers. For example, the
405 Method Not Allowed
header should contain an
Allow header, and the
503 Service Unavailable
should have a
Retry-After header. The built-in error classes include support
;trycatch etrycatch e
Lastly, it the package has an interface that makes it easier to work with the
application/problem+json format, as defined in RFC7807. The interface
instance properties, which makes it easier
to write a generic interface that emits this JSON error format.