Nodejs - errorHandlers Middleware
const chalk = require('chalk');
// Declare the debug module
let debug = {};
debug.log = message => console.log(chalk.magenta.bgYellow.underline(message));
debug.info = message => console.log(chalk.blue(message));
debug.warn = message => console.log(chalk.yellow(message));
debug.error = message => console.log(chalk.red(message));
debug.wtf = message => console.log(chalk.magenta.bold(message));
module.exports = debug;
const debug = require('../functions/debug');
const logger = require('../functions/logger');
/*
Catch Errors Handler
With async/await, you need some way to catch errors
Instead of using try{} catch(e) {} in each controller, we wrap the function in
catchErrors(), catch any errors they throw, and pass it along to our express middleware with next()
Note: Don't use catchErrors with Promise
*/
exports.catchErrors = fn => {
return function(req, res, next) {
return fn(req, res, next).catch(next);
};
};
/*
Not Found Error Handler
If we hit a route that is not found, we mark it as 404 and pass it along to the next error handler to display
*/
exports.notFound = (req, res, next) => {
const err = new Error('Not Found!');
err.status = 404;
next(err);
};
// Development Errors Handlers
exports.developmentErrors = (err, req, res, next) => {
const status = err.status || 500;
const message = err.message || 'Internal Server Error!';
if (status === 404) {
return res.status(status).json({ message: message });
}
debug.error(err.stack);
logger.error(err.stack);
res.status(status).json({ message: message, error: err.stack });
};
/*
Production Error Handler
No stacktraces are leaked to user
*/
exports.productionErrors = (err, req, res, next) => {
const status = err.status || 500;
const message = err.message || 'Internal Server Error!';
debug.error(err);
logger.error(err.stack);
res.status(status).json({ message: message });
};
const winston = require('winston');
const { combine, timestamp, prettyPrint, simple, label } = winston.format;
require('winston-daily-rotate-file');
const path = require('path');
const rootPath = require('./rootPath');
const moment = require('moment');
let year = moment().format('YYYY');
let month = moment().format('MM');
let location = path.join(rootPath, '.logs', year, month);
let transport = new winston.transports.DailyRotateFile({
dirname: location,
filename: '%DATE%.json',
datePattern: 'DD',
zippedArchive: true,
maxSize: '20m',
maxFiles: '14d'
});
transport.on('rotate', function(oldFilename, newFilename) {
// do something here
});
let logger = winston.createLogger({
format: combine(timestamp(), prettyPrint()),
transports: [transport]
});
module.exports = logger;