@greylocklabs/http
Utilities for working with HTTP status codes, errors, and more
This package provides a series of useful Node.js modules meant for use in web servers. The following utilities are included:
-
status
- HTTP status code utilities -
errors
- Custom HTTP errors for use in Koa, Express, etc. -
createError
function - Create an HTTP error from a status code
Additionally, a createError(statusCode, message)
function is provided so you can easily create the
correct ClientError
or ServerError
from an HTTP status code. Useful in cases where you're interacting
with a third-party API and might not know what status codes to expect. See below for examples.
Installation
Install using npm
:
$ npm install @greylocklabs/http
Usage
Here's a basic web server using the Koa framework as an example:
import Koa from 'koa';
import Router from 'koa-router';
import { createError, errors, status } from '../src';
const app = new Koa();
const router = new Router();
router.get('/api', async (ctx, next) => {
await next();
ctx.status = status.OK; // 200
ctx.message = status[200]; // 'OK'
ctx.body = {
api: 'running',
};
});
router.get('/errors/404', () => {
throw new errors.NotFoundError('Nothing to see here!'); // error exposed to client by default
});
router.get('/errors/500', () => {
throw new errors.InternalServerError('Something broke!'); // only shows "Internal Server Error" publicly
});
router.get('/custom/:code', (ctx) => {
throw createError(ctx.params.code); // throws the error that corresponds to the status code provided
});
app.use(router.routes());
app.listen(3000, () => {
console.log('App is listening on port 3000...');
});
More examples can be found here!
Documentation
The documentation can be viewed here.
Contributing
See CONTRIBUTING.md for details.
License
MIT License. See LICENSE file for details.