Express library
The library with common, often used middlewares and utilites.
Installation
npm install --save express-lib
const {bodyNotEmpty, ...} = require('express-lib');
Usage
Middlewares:
bodyNotEmpty
catchError
errorsMainHandler
getOr404
Utils:
notFoundError
internalServerError
badRequestError
conflictError
getHttpError
bodyNotEmpty()
Middleware that checks is body in request is empty or not present.
If it does then calls next()
with Bad Request error
Example:
const bodyNotEmpty = ; app
catchError(middlewareFunc)
Wraps middleware function to catch any thown error in it and pass to next()
.
Example:
const catchError = ; app
errorsMainHandler({ showStack = true, logger })
Middleware that catches all errors passed to next()
and calls response in json format like
code: 404 message: 'Not Found' stack: stacktrace // Can be omitted
Should be the last middleware in the app.
Receives optional params:
- showStack
(true by default) - Show/hide stacktrace
- logger
- if specified make call logger.error() with received error
Example:
const errorsMainHandler = ;const logger = console; app app; // Will call response with status (404), and json data: // {// code: 404,// message: 'Not Found'// }
getOr404(fieldName, getFunction, customErrorMessage)
Middleware that calls getFunction(req)
to retrieve some data and populates res.locals
object with field fieldName
and retrieved data.
If getFunction
returns undefined then next()
with "Not Found" error calls.
customErrorMessage
- is optional and overrides default 'Not Found' message
Example
const getOr404 = ; app
getHttpError(message, httCode)
Received message and httpCode and returns Error instance and assigned status code
Example
const getHttpError = ; const e = ;console // "Bad Request"console // 400;
Different HTTP Errors utilites
This functions creates new Error instaces and assings http code and type.
- notFoundError(message = 'Not Found')
- internalServerError(message = 'Internal Server Error')
- badRequestError(message = 'Bad Request')
- conflictError(message = 'Conflict')
Example:
const notFoundError internalServerError badRequestError conflictError = ; app