NODE_ENV =生产时忽略错误处理程序

问题描述 投票:7回答:1

我正在使用Node / Express构建一个简单的REST API,当我将其部署到生产环境时,我很难。当NODE_ENV=development,一切都按预期工作。我找回了JSON错误和正确的状态代码。当NODE_ENV=production时,我只返回一个带有默认错误消息的HTML页面,而不是其他任何内容。我可以读取状态代码,但我需要访问完整的JSON有效负载以更好地识别错误。这是我的代码:

import Promise from 'bluebird'; // eslint-disable-line no-unused-vars
import express from 'express';
import config from './config';
import routes from './routes';
import { errorMiddleware, notFoundMiddleware } from './middlewares/error.middleware';
import mongoose from './config/mongoose.config';

// create app
const app = express();

(async () => {
  // connect to mongoose
  await mongoose.connect();

  // pretty print on dev
  if (process.env.NODE_ENV !== 'production') {
    app.set('json spaces', 2);
  }

  // apply express middlewares
  app.use(express.json());

  // register v1 routes
  app.use('/v1', routes);

  // catch errors
  app.use(notFoundMiddleware);
  app.use(errorMiddleware);

  // start server
  app.listen(config.port, () => console.info(`server started on port ${config.port}`));
})();

export default app;

这是notFoundMiddleware

export default (req, res, next) => next(new Error('Not Found'));

这是errorMiddleware

const errorMiddleware = (err, req, res, next) => {
  console.log('test'); // this works in development, but not in production
  const error = {
    status: err.status,
    message: err.message
  };

  if (err.errors) {
    error.errors = err.errors;
  }

  if (process.env.NODE_ENV !== 'production' && err.stack) {
    error.stack = err.stack;
  }

  return res.status(error.status || 500).send({ error });
};
json node.js api express error-handling
1个回答
0
投票

如果您在生产服务器上运行,请尝试使用某些日志记录提供程序(如“papertrail”)来查看应用程序中发生的错误。

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.