How do I turn off Node.js Express (ejs template engine) errors for production?

后端 未结 2 522
逝去的感伤
逝去的感伤 2021-01-01 02:31

When I\'m on a development server and there is an error, Express sends the traceback as a response.

However, this is not good for production. I don\'t want anyone se

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-01 02:50

    The latest version of Express use smart default error handler.

    In development mode it sends full stack trace back to the browser, while in production mode it sends only 500 Internal Server Error.

    To take advantage of it you should set proper NODE_ENV before running your application.

    For example, to run your app in production mode:

    NODE_ENV=production node application.js
    

    But if you don't like this default behavior, you could define your own error handler:

    app.use(function(err, req, res, next){
      console.error(err);
      res.status(500);
      res.render('error');
    });
    

    Note that error handler must be the last middleware in chain, so it should be defined in the bottom of your application.js file.


    If you need more information, see:

    • Express official documentation
    • Blog post about error handling in Express

提交回复
热议问题