filesafe/controllers/handlers/apiErrorsHandler.js
Bobby Wibowo ae31033c0c
refactor: init UserError, a custom Error object
This will be used for errors that are to be delivered to users, AND not
to be logged into the server (as in it stacktraces and all).
This will eventually remove the need to throw string literals.

In this commit, this has only been implemented on albumsController.js,
but more will soon to come.
2021-01-08 07:29:14 +07:00

31 lines
802 B
JavaScript

const UserError = require('./../utils/UserError')
const logger = require('./../../logger')
module.exports = (error, req, res, next) => {
if (!res) {
return logger.error(new Error('Missing "res" object.'))
}
// Intentional error messages to be delivered to users
const isUserError = error instanceof UserError
// ENOENT or missing file errors, typically harmless, so do not log stacktrace
const isENOENTError = error instanceof Error && error.code === 'ENOENT'
if (!isUserError && !isENOENTError) {
logger.error(error)
}
const statusCode = isUserError
? error.statusCode
: 500
const description = isUserError
? error.message
: 'An unexpected error occurred. Try again?'
return res
.status(statusCode)
.json({ success: false, description })
}