mirror of
https://github.com/BobbyWibowo/lolisafe.git
synced 2024-12-15 08:56:21 +00:00
b35f4ae6eb
this required expanding our custom error classes with support for arbitrary internal api error codes however it'll only be used for invalid token errors for now (10001) no plan to assign codes to other existing api errors at that point it's probably better to redo the whole api infrastructure
44 lines
1.1 KiB
JavaScript
44 lines
1.1 KiB
JavaScript
const ClientError = require('./../utils/ClientError')
|
|
const ServerError = require('./../utils/ServerError')
|
|
const logger = require('./../../logger')
|
|
|
|
module.exports = (error, req, res, next) => {
|
|
if (!res) {
|
|
return logger.error(new Error('Missing "res" object.'))
|
|
}
|
|
|
|
// Error messages that can be returned to users
|
|
const isClientError = error instanceof ClientError
|
|
const isServerError = error instanceof ServerError
|
|
|
|
const logStack = (!isClientError && !isServerError) ||
|
|
(isServerError && error.logStack)
|
|
if (logStack) {
|
|
logger.error(error)
|
|
}
|
|
|
|
const statusCode = (isClientError || isServerError)
|
|
? error.statusCode
|
|
: 500
|
|
|
|
const json = {}
|
|
|
|
const description = (isClientError || isServerError)
|
|
? error.message
|
|
: 'An unexpected error occurred. Try again?'
|
|
if (description) {
|
|
json.description = description
|
|
}
|
|
|
|
if ((isClientError || isServerError) && error.code) {
|
|
json.code = error.code
|
|
}
|
|
|
|
if (Object.keys(json).length) {
|
|
json.success = false
|
|
return res.status(statusCode).json(json)
|
|
} else {
|
|
return res.status(statusCode).end()
|
|
}
|
|
}
|