@mantris/appify
Version:
Very opinionated Node.js API boilerplate as module.
61 lines (52 loc) • 1.64 kB
JavaScript
const { HttpError } = require('@mantris/commons')
const ERROR_MESSAGE = 'Oh no! Something went wrong on our end.'
/**
* @param {HttpError} err Error instance.
* @param {String} environment Environment name.
* @param {String} genericmessage Generic displayable error message.
* @returns {String} Displayable error message.
*/
const getMessage = (err, environment, genericmessage) => {
if (err.status < 500) {
return err.message
}
return environment !== 'production'
? err.message
: genericmessage
}
/**
* @param {HttpError} err Error instance.
* @param {String} environment Environment name.
* @returns {String|undefined} Displayable stack.
*/
const getStack = (err, environment) => {
return err.status >= 500 && environment !== 'production'
? err.stack
: undefined
}
/**
* @param {HttpError} err Error instance.
* @param {String} environment Environment name.
* @returns {Object[]|undefined} Displayable stack.
*/
const getDetails = (err) => {
return err instanceof HttpError.BadRequest || err instanceof HttpError.UnprocessableEntity
? err.details
: undefined
}
/**
* @params {String} environment Current environment name.
* @returns {Function} Middleware.
*/
module.exports = (environment) => {
return (err, req, res, next) => {
const { code, status } = err
const stack = getStack(err, environment)
const message = getMessage(err, environment, ERROR_MESSAGE)
const details = getDetails(err)
res
.status(status)
.json({ status, error: { code, message, stack, details } })
}
}