2022-07-10 07:10:59 +00:00
|
|
|
const path = require('path')
|
|
|
|
const paths = require('./pathsController')
|
|
|
|
const ClientError = require('./utils/ClientError')
|
|
|
|
const ServerError = require('./utils/ServerError')
|
2022-10-05 19:39:51 +00:00
|
|
|
const config = require('./utils/ConfigManager')
|
2022-07-12 01:51:22 +00:00
|
|
|
const logger = require('./../logger')
|
2022-07-10 07:10:59 +00:00
|
|
|
|
|
|
|
const self = {
|
|
|
|
errorPagesCodes: Object.keys(config.errorPages)
|
|
|
|
.filter(key => /^\d+$/.test(key))
|
|
|
|
.map(key => Number(key))
|
|
|
|
}
|
|
|
|
|
2022-07-11 23:21:21 +00:00
|
|
|
self.handleError = (req, res, error) => {
|
2022-07-10 07:10:59 +00:00
|
|
|
if (!res || res.headersSent) {
|
2023-09-06 12:00:42 +00:00
|
|
|
logger.error(error)
|
|
|
|
return
|
2022-07-10 07:10:59 +00:00
|
|
|
}
|
|
|
|
|
2022-07-21 16:56:08 +00:00
|
|
|
res.header('Cache-Control', 'no-store')
|
|
|
|
|
|
|
|
// Errors that should be returned to users as JSON payload
|
2022-07-10 07:10:59 +00:00
|
|
|
const isClientError = error instanceof ClientError
|
|
|
|
const isServerError = error instanceof ServerError
|
|
|
|
|
2022-07-21 16:56:08 +00:00
|
|
|
let statusCode = res.statusCode
|
2022-07-10 07:10:59 +00:00
|
|
|
|
2022-07-21 16:56:08 +00:00
|
|
|
if (isClientError || isServerError) {
|
|
|
|
if (isServerError && error.logStack) {
|
|
|
|
logger.error(error)
|
|
|
|
}
|
2022-07-10 07:10:59 +00:00
|
|
|
|
2022-07-21 16:56:08 +00:00
|
|
|
const json = {
|
|
|
|
success: false,
|
|
|
|
description: error.message || 'An unexpected error occurred. Try again?',
|
|
|
|
code: error.code
|
|
|
|
}
|
2022-07-10 07:10:59 +00:00
|
|
|
|
2022-07-21 16:56:08 +00:00
|
|
|
if (statusCode === undefined) {
|
|
|
|
res.status(error.statusCode || 500)
|
|
|
|
}
|
2022-07-10 07:10:59 +00:00
|
|
|
|
2022-07-21 16:56:08 +00:00
|
|
|
return res.json(json)
|
|
|
|
} else {
|
|
|
|
// Generic Errors
|
|
|
|
logger.error(error)
|
2022-07-10 07:10:59 +00:00
|
|
|
|
2022-07-21 16:56:08 +00:00
|
|
|
if (statusCode === undefined) {
|
|
|
|
statusCode = 500
|
|
|
|
}
|
2022-07-10 07:10:59 +00:00
|
|
|
|
|
|
|
if (self.errorPagesCodes.includes(statusCode)) {
|
2022-07-21 16:56:08 +00:00
|
|
|
return res
|
|
|
|
.status(statusCode)
|
|
|
|
.sendFile(path.join(paths.errorRoot, config.errorPages[statusCode]))
|
2022-07-10 07:10:59 +00:00
|
|
|
} else {
|
2022-07-21 16:56:08 +00:00
|
|
|
return res
|
|
|
|
.status(statusCode)
|
|
|
|
.end()
|
2022-07-10 07:10:59 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-07-11 23:21:21 +00:00
|
|
|
self.handleNotFound = (req, res) => {
|
2023-09-06 12:00:42 +00:00
|
|
|
if (!res || res.headersSent) return
|
|
|
|
|
2022-07-21 13:28:10 +00:00
|
|
|
res.header('Cache-Control', 'no-store')
|
2022-07-21 16:56:08 +00:00
|
|
|
return res
|
|
|
|
.status(404)
|
|
|
|
.sendFile(path.join(paths.errorRoot, config.errorPages[404]))
|
2022-07-10 07:10:59 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = self
|