filesafe/controllers/errorsController.js

74 lines
1.7 KiB
JavaScript
Raw Normal View History

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')
const logger = require('./../logger')
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) => {
if (!res || res.headersSent) {
2023-09-06 12:00:42 +00:00
logger.error(error)
return
}
res.header('Cache-Control', 'no-store')
// 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]))
} else {
return res
.status(statusCode)
.end()
}
}
}
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
res.header('Cache-Control', 'no-store')
return res
.status(404)
.sendFile(path.join(paths.errorRoot, config.errorPages[404]))
}
module.exports = self