@wizim-dev/bim
v0.0.1
Published
HTTP-friendly error objects
Maintainers
Readme
Bim
HTTP-friendly error objects
Bim provides a set of utilities for returning HTTP errors. Each utility returns a Bim error response object which includes the following properties:
isServer- convenience bool indicating status code >= 500.isDeveloperError- convenience bool indicating error due to developper (i.e badImplementation constructor)statusCode- the HTTP status code (typically 4xx or 5xx).output- the formatted errors output.- inherited
Errorproperties.
Install
npm install '@snark/bim'Usage
Bim.badImplementation(new Error('Should not be here'))Generates the following payload
[
{
"id": "Internal.BadImplementation"
}
]Advanced Usage
import express from 'express';
import bim from './modules/bim';
const app = express();
app.use(bim.expressErrorMiddleware(console, process.env.NODE_ENV));
const loginSchema = {
body: {
username: bim.Joi.string().required(),
password: bim.Joi.string().required()
}
}
app.use('/login', bim.validate(loginSchema), (req, res, next) => {
if (req.body.username !== 'admin') {
next(bim.unauthorized('Username is not valid').id('Auth.Username.Invalid'));
} else {
console.log("You rocks!");
}
})Documentation
- Helper methods
- HTTP 4xx Errors
Bim.badRequest([message])Bim.unauthorized([message])Bim.paymentRequired([message])Bim.forbidden([message])Bim.notFound([message])Bim.methodNotAllowed([message])Bim.notAcceptable([message])Bim.proxyAuthRequired([message])Bim.clientTimeout([message])Bim.conflict([message])Bim.resourceGone([message])Bim.lengthRequired([message])Bim.preconditionFailed([message])Bim.entityTooLarge([message])Bim.uriTooLong([message])Bim.unsupportedMediaType([message])Bim.rangeNotSatisfiable([message])Bim.expectationFailed([message])Bim.teapot([message])Bim.badData([message])Bim.locked([message])Bim.failedDependency([message])Bim.preconditionRequired([message])Bim.tooManyRequests([message])Bim.illegal([message])
- HTTP 5xx Errors
Helper methods
new Bim(message, statusCode, ctor)
Creates a new Bim object to decorate the error with the Bim properties, where:
message- the error message or directly an instance object ofErrorstatusCode- the HTTP status code. Defaults to500if no status code is already set.ctor- constructor reference used to crop the exception call stack output.
The Bim object support chained method id(), context() and data() to add information about the error
id(identifier)
Add an unique identifier to the error object
context(key)
Add context key to the error object (useful for form)
data(data)
Add data information to the error object
error(identifier, context, data)
Helper to add an error into output
errors(errors)
Helper to add multiple errors into output
isBim(err)
Identifies whether an error is a Bim object. Same as calling instanceof Bim.
expressErrorMiddleware(logger, environment)
Express middleware helper to handle Bim errors
logger- logger instance to use in express middleware (default:console)environment- (default:'production')
graphQLFormatError(logger, environment)
GraphQL helper to format Bim errors
logger- logger instance to use in express middleware (default:console)environment- (default:'production')
validate(schema, options)
Return a middleware to validate Joi schema
Generate a Bim.badData() in case of failure.
schema-Joischema objectoptions- options given toJoi.validate()method
HTTP 4xx Errors
Bim.badRequest([message])
Returns a 400 Bad Request error where:
message- optional message orErrorinstance.
Bim.badRequest('invalid query');Bim.unauthorized([message])
Returns a 401 Unauthorized error
Bim.unauthorized('invalid password');Bim.paymentRequired([message])
Returns a 402 Payment Required error where:
message- optional message orErrorinstance.
Bim.paymentRequired('bandwidth used');Bim.forbidden([message])
Returns a 403 Forbidden error where:
message- optional message orErrorinstance.
Bim.forbidden('try again some time');Bim.notFound([message])
Returns a 404 Not Found error where:
message- optional message orErrorinstance.
Bim.notFound('missing');Bim.methodNotAllowed([message])
Returns a 405 Method Not Allowed error where:
message- optional message orErrorinstance.
Bim.methodNotAllowed('that method is not allowed');Bim.notAcceptable([message])
Returns a 406 Not Acceptable error where:
message- optional message orErrorinstance.
Bim.notAcceptable('unacceptable');Bim.proxyAuthRequired([message])
Returns a 407 Proxy Authentication Required error where:
message- optional message orErrorinstance.
Bim.proxyAuthRequired('auth missing');Bim.clientTimeout([message])
Returns a 408 Request Time-out error where:
message- optional message orErrorinstance.
Bim.clientTimeout('timed out');Bim.conflict([message])
Returns a 409 Conflict error where:
message- optional message orErrorinstance.
Bim.conflict('there was a conflict');Bim.resourceGone([message])
Returns a 410 Gone error where:
message- optional message orErrorinstance.
Bim.resourceGone('it is gone');Bim.lengthRequired([message])
Returns a 411 Length Required error where:
message- optional message orErrorinstance.
Bim.lengthRequired('length needed');Bim.preconditionFailed([message])
Returns a 412 Precondition Failed error where:
message- optional message orErrorinstance.
Bim.preconditionFailed();Bim.entityTooLarge([message])
Returns a 413 Request Entity Too Large error where:
message- optional message orErrorinstance.
Bim.entityTooLarge('too big');Bim.uriTooLong([message])
Returns a 414 Request-URI Too Large error where:
message- optional message orErrorinstance.
Bim.uriTooLong('uri is too long');Bim.unsupportedMediaType([message])
Returns a 415 Unsupported Media Type error where:
message- optional message orErrorinstance.
Bim.unsupportedMediaType('that media is not supported');Bim.rangeNotSatisfiable([message])
Returns a 416 Requested Range Not Satisfiable error where:
message- optional message orErrorinstance.
Bim.rangeNotSatisfiable();Bim.expectationFailed([message])
Returns a 417 Expectation Failed error where:
message- optional message orErrorinstance.
Bim.expectationFailed('expected this to work');Bim.teapot([message])
Returns a 418 I'm a Teapot error where:
message- optional message orErrorinstance.
Bim.teapot('sorry, no coffee...');Bim.badData([message])
Returns a 422 Unprocessable Entity error where:
message- optional message orErrorinstance.
Bim.badData('your data is bad and you should feel bad');Bim.locked([message])
Returns a 423 Locked error where:
message- optional message orErrorinstance.
Bim.locked('this resource has been locked');Bim.failedDependency([message])
Returns a 424 Failed Dependency error where:
message- optional message orErrorinstance.
Bim.failedDependency('an external resource failed');Bim.preconditionRequired([message])
Returns a 428 Precondition Required error where:
message- optional message orErrorinstance.
Bim.preconditionRequired('you must supply an If-Match header');Bim.tooManyRequests([message])
Returns a 429 Too Many Requests error where:
message- optional message orErrorinstance.
Bim.tooManyRequests('you have exceeded your request limit');Bim.illegal([message])
Returns a 451 Unavailable For Legal Reasons error where:
message- optional message orErrorinstance.
Bim.illegal('you are not permitted to view this resource for legal reasons');HTTP 5xx Errors
All 500 errors
Set by default isServer to true
Bim.badImplementation([message])
Set isDeveloperError to true Returns a 500 Internal Server Error error where:
message- optional message orErrorinstance.
Bim.badImplementation('terrible implementation');Bim.notImplemented([message])
Returns a 501 Not Implemented error where:
message- optional message orErrorinstance.
Bim.notImplemented('method not implemented');Bim.badGateway([message])
Returns a 502 Bad Gateway error where:
message- optional message orErrorinstance.
Bim.badGateway('that is a bad gateway');Bim.serverUnavailable([message])
Returns a 503 Service Unavailable error where:
message- optional message orErrorinstance.
Bim.serverUnavailable('unavailable');Bim.gatewayTimeout([message])
Returns a 504 Gateway Time-out error where:
message- optional message orErrorinstance.
Bim.gatewayTimeout();