errdrop
A lightweight drop-in Error
replacement with take-it-or-leave-it HTTP status code support.
Useful for preserving associations between errors and their appropriate HTTP status codes when decoupling application logic from middleware plumbing.
Installation
npm i errdrop
yarn add errdrop
Example
const Error = require('errdrop')
function sayHello(name) {
switch (name) {
case 'Dwight':
throw new Error.Forbidden(`Go away, ${name}.`)
case 'Michael':
throw new Error.MovedPermanently()
default:
return `Hello, ${name}!`
}
}
app.get('/say-hello/:name', (req, res) => {
try {
res.send(sayHello(req.params.name))
}
catch (err) {
res.status(err.statusCode || 500).send(err.message)
}
})
Supported status codes
Subclasses are generated for each entry in http.STATUS_CODES
. See here for the full list.
These classes pass all arguments through to Error
for full drop-in compatibility.
Custom or nonstandard status codes are supported via the generic Error.StatusCode
class, which prepends the Error
class signature with a status code parameter:
throw new Error.StatusCode(218, 'This is fine')
thinware
support
This module pairs well with thinware, which honors status codes attached to thrown Error
objects:
app.get('/say-hello/:name',
thinware(sayHello, req => req.params.name)
)