-
Notifications
You must be signed in to change notification settings - Fork 5
/
ErrorHandler.js
30 lines (24 loc) · 1016 Bytes
/
ErrorHandler.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
'use strict';
const expressValidation = require('express-validation');
const log = require('./config/logger');
const errors = require('./errors');
module.exports = (app) => {
const error_code = {
INVALID_PARAMETER: 9401,
SERVER_ERROR: 500
};
app.use((err, req, res, next) => {
// Custom error logging title.
const log_title = `\n\x1b[31m[ERROR Handler]\u001b[0m\n\x1b[34m[Request PATH - ${req.path}]\u001b[0m\n`;
// Custom error division.
let response = errors[isNaN(err) ? error_code.SERVER_ERROR : err];
if (err instanceof expressValidation.ValidationError) { // Wrong Parameter
response = errors[error_code.INVALID_PARAMETER];
response.miss_param = err.errors.map(error => error.messages.join('. ')).join('\n');
}
// Custom error logging.
log.error(log_title.concat(typeof response.miss_param !== 'undefined' ?
`\x1b[36m[Miss Params] \u001b[0m \n${response.miss_param}` : err));
return res.status(response.status).json(response);
});
};