Search code examples
javascriptnode.jsexpressecmascript-6winston

Create new Object() in catch block js


import express from 'express';
import route from './server/routes/route';
import cookieParser from 'cookie-parser';
import bodyParser from 'body-parser';
import favicon from 'serve-favicon';
import path from 'path';
import Logger from './server/logger/logger.js';

try {
  const app = express();
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({extended: false}));
  app.use(cookieParser());
  app.use(favicon(path.join(__dirname, '/client/assets/favicon.ico')));
  app.use(express.static(path.join(__dirname, 'client')));
  app.use(route);
  app.listen(3000);
  new Logger().logInfo('Server started at port 3000');
} catch (e) {
  new Logger().logError(e);
  process.exit(1);
}

process.on('uncaughtException', function (err) {
  process.exit(1);
  new Logger().logError(err);
});

Here i am trying to create an express server. I used a try catch block. When i remove the import path from 'path' an error is generated and the catch is called. However the problem is new Logger().logError(e); not working. it is supposed to log error into a certain file. But nothing is happening. But if there is no error, then the logInfo() is working alright. I tried logging to console and it is working. I am using babel so is it a problem with that ? Logger is a class which contain a winston logger implementation and exposes methods logError and logInfo.


Solution

  • It is a known bug in winston and it seems they are not going to patch it. I have used one of the workarounds provided there and everything works fine. Here

    this.winstonlogger.log('error', logMessage, () => {
      this.transports.file.on('flush', () => {
        process.exit(1);
      });
    });