I am trying to find a way to catch all errors in my project and save them to the database as well as file log. I have create the following middleware which helps me in that need but the only problem I am facing using winston is that once uncaughtException or unhandledRejection is handled the app is terminated. Is there a way in winston to avoid this termination. All I want if for the them to be saved and delt later on.
const winston = require('winston');
require('winston-mongodb');
module.exports = function () {
process.on('unhandledRejection', (ex) => {
//console.error('error', ex);
throw ex; //Find better way
});//Catching uncaught exceptions with winston. We are using both file and db.
winston.exceptions.handle([
new winston.transports.MongoDB({
db: 'mongodb://localhost/web_logs',
collection: 'exceptions',
level: 'error'
}),
new winston.transports.Console,
new winston.transports.File({filename: 'web-exceptions.log'})
]
);};
It is used in express after routes as
require('./middleware/exception-handler')();
It works well as intended but it terminates the app. How to avoid that?
Do have an expressjs error handling middleware function ? // something like this in ur index.js or app.js file
`app.use(function (err, req, res, next) {
console.error(err.stack)
res.status(500).send('Something broke!')
});`
winstonjs logs the errors, but they are not catch so it will crash your app