From 1b4b73b67cd9cffc070be803d6f530f6764a11b9 Mon Sep 17 00:00:00 2001 From: Bobby Wibowo Date: Thu, 21 Jul 2022 23:56:08 +0700 Subject: [PATCH] feat: improved errorsController.js mainly handling generic errors --- controllers/errorsController.js | 75 ++++++++++++++++++--------------- 1 file changed, 40 insertions(+), 35 deletions(-) diff --git a/controllers/errorsController.js b/controllers/errorsController.js index c602cee..8e6db29 100644 --- a/controllers/errorsController.js +++ b/controllers/errorsController.js @@ -13,54 +13,59 @@ const self = { self.handleError = (req, res, error) => { if (!res || res.headersSent) { - console.error('Error: Unexpected missing "res" object or headers alredy sent.') - return console.error(error) - } - - // 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 + logger.error('Error: Unexpected missing "res" object or headers alredy sent.') + return logger.error(error) } res.header('Cache-Control', 'no-store') - if (Object.keys(json).length) { - json.success = false - return res.status(statusCode).json(json) + // Errors that should be returned to users as JSON payload + const isClientError = error instanceof ClientError + const isServerError = error instanceof ServerError + + let statusCode = res.statusCode + + if (isClientError || isServerError) { + if (isServerError && error.logStack) { + logger.error(error) + } + + const json = { + success: false, + description: error.message || 'An unexpected error occurred. Try again?', + code: error.code + } + + if (statusCode === undefined) { + res.status(error.statusCode || 500) + } + + return res.json(json) } else { + // Generic Errors + logger.error(error) + + if (statusCode === undefined) { + statusCode = 500 + } + if (self.errorPagesCodes.includes(statusCode)) { - return res.status(statusCode).sendFile(path.join(paths.errorRoot, config.errorPages[statusCode])) + return res + .status(statusCode) + .sendFile(path.join(paths.errorRoot, config.errorPages[statusCode])) } else { - return res.status(statusCode).end() + return res + .status(statusCode) + .end() } } } self.handleNotFound = (req, res) => { res.header('Cache-Control', 'no-store') - return res.status(404).sendFile(path.join(paths.errorRoot, config.errorPages[404])) + return res + .status(404) + .sendFile(path.join(paths.errorRoot, config.errorPages[404])) } module.exports = self