2021-01-08 01:44:28 +00:00
|
|
|
const ClientError = require('./../utils/ClientError')
|
|
|
|
const ServerError = require('./../utils/ServerError')
|
2021-01-08 00:29:14 +00:00
|
|
|
const logger = require('./../../logger')
|
|
|
|
|
|
|
|
module.exports = (error, req, res, next) => {
|
|
|
|
if (!res) {
|
|
|
|
return logger.error(new Error('Missing "res" object.'))
|
|
|
|
}
|
|
|
|
|
2021-01-08 01:44:28 +00:00
|
|
|
// Error messages that can be returned to users
|
|
|
|
const isClientError = error instanceof ClientError
|
|
|
|
const isServerError = error instanceof ServerError
|
2021-01-08 00:29:14 +00:00
|
|
|
|
2021-01-08 01:44:28 +00:00
|
|
|
const logStack = (!isClientError && !isServerError) ||
|
|
|
|
(isServerError && error.logStack)
|
|
|
|
if (logStack) {
|
2021-01-08 00:29:14 +00:00
|
|
|
logger.error(error)
|
|
|
|
}
|
|
|
|
|
2021-01-08 01:44:28 +00:00
|
|
|
const statusCode = (isClientError || isServerError)
|
2021-01-08 00:29:14 +00:00
|
|
|
? error.statusCode
|
|
|
|
: 500
|
|
|
|
|
2021-01-08 01:44:28 +00:00
|
|
|
const description = (isClientError || isServerError)
|
2021-01-08 00:29:14 +00:00
|
|
|
? error.message
|
|
|
|
: 'An unexpected error occurred. Try again?'
|
|
|
|
|
2021-01-08 03:11:56 +00:00
|
|
|
if (description) {
|
2021-01-08 20:50:03 +00:00
|
|
|
return res.status(statusCode).json({ success: false, description })
|
2021-01-08 03:11:56 +00:00
|
|
|
} else {
|
2021-01-08 20:50:03 +00:00
|
|
|
return res.status(statusCode).end()
|
2021-01-08 03:11:56 +00:00
|
|
|
}
|
2021-01-08 00:29:14 +00:00
|
|
|
}
|