代码之家  ›  专栏  ›  技术社区  ›  Juned Ansari

防止在未捕获异常后崩溃节点js

  •  2
  • Juned Ansari  · 技术社区  · 7 年前

    我如何防止撞车?

    const express = require('express');
    const winston = require("winston");
    const app = express();
    
    //Logging is responsible to log and display errors
    require('./startup/logging')();
    //routes will contains all the routes list
    require('./startup/routes')(app);
    
    //PORT
    const port = process.env.PORT || 3000;
    app.listen(port,() => winston.info(`Listening on port ${port}....`));
    

    日志.js

    const express = require('express');
    const winston = require('winston');
    // require('express-async-errors');
    
    module.exports = function() {
      winston.handleExceptions(
        new winston.transports.File({ filename: 'uncaughtExceptions.log' })
      );
    
      process.on('unhandledRejection', (ex) => {
        throw ex;
      });
    
      winston.add(winston.transports.File, { filename: 'error.log' });
    
    }
    
    1 回复  |  直到 7 年前
        1
  •  4
  •   Estus Flask    7 年前

    作为 the documentation

    默认情况下,winston将在记录未捕获的异常后退出。如果这不是您想要的行为,请设置exitOnError=false

    const logger = winston.createLogger({ exitOnError: false });
    
    //
    // or, like this:
    //
    logger.exitOnError = false;
    

    通常认为在异常之后不退出是一种不好的做法,因为其后果是不可预测的。如果已知只有一些异常是可容忍的,则可以使用谓词具体地处理它们:

    const ignoreWarnings = err => !(err instanceof WarningError);
    
    const logger = winston.createLogger({ exitOnError: ignoreWarnings });
    
    推荐文章