表示不会在中间件中捕获异常

时间:2017-10-04 20:17:14

标签: node.js express

我试图使用中间件来捕获路由中的异常。

预期结果:

当路由中抛出错误时,我希望它被中间件捕获,这样我就可以记录错误并返回一般响应。

实际结果:

当路由中出现错误时,永远不会到达中间件。错误和堆栈跟踪将打印到控制台,浏览器将显示Internal Server Error。抛出的除外:

> NODE_ENV=production node api/server.js

Listening on port 8080!
Error: Error in /invite route
    at app.get (/Users/bughunter/Projects/ooberoo/lander/api/server.js:42:8)
    at Layer.handle [as handle_request] (/Users/bughunter/Projects/ooberoo/lander/node_modules/express/lib/router/layer.js:95:5)
    at next (/Users/bughunter/Projects/ooberoo/lander/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/Users/bughunter/Projects/ooberoo/lander/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/Users/bughunter/Projects/ooberoo/lander/node_modules/express/lib/router/layer.js:95:5)
    at /Users/bughunter/Projects/ooberoo/lander/node_modules/express/lib/router/index.js:281:22
    at Function.process_params (/Users/bughunter/Projects/ooberoo/lander/node_modules/express/lib/router/index.js:335:12)
    at next (/Users/bughunter/Projects/ooberoo/lander/node_modules/express/lib/router/index.js:275:10)
    at Layer.handle [as handle_request] (/Users/bughunter/Projects/ooberoo/lander/node_modules/express/lib/router/layer.js:91:12)

应用程序从npm start脚本运行:

"start": "NODE_ENV=production node api/server.js",

我的代码如下:

const express = require('express');
const path = require('path');
const winston = require('winston');
require('winston-daily-rotate-file');

// Are we production or development?
const env = process.env.NODE_ENV || 'development';

// Express
const app = express();

// Logger
const logger = new (winston.Logger)({
  transports: [ 
    new (winston.transports.DailyRotateFile)({
      filename: path.resolve(__dirname, '../logs/app.log'),
      datePattern: 'yyyy-MM-dd.',
      prepend: true,
      level: process.env.ENV === 'development' ? 'debug' : 'info'
    })
   ]
});

// Static files
app.use(express.static(path.resolve(__dirname, 'static')));

// Generic error middleware
app.use(function(error, req, res, next) {
  logger.log('error', error);
  res.status(500);
  res.setHeader('Content-Type', 'application/json');
  res.json({ error: 'Failed to process request' });
});

// Homepage
app.get('/', (req, res) =>
  res.sendFile(path.resolve(__dirname, './static/index.html'))
);

// Invite signup
app.get('/invite', (req, res, next) => {
  next(new Error('Error in /invite route'));
});

// Redirect to home if no route found
app.get('*', (req, res) =>
  res.redirect('/')
);

app.listen(8080, () =>
  console.log('Listening on port 8080!')
);

我正在documentation做它所说的但它似乎不起作用。这里有什么建议吗?

1 个答案:

答案 0 :(得分:2)

必须在所有其他中间件和路由之后的最后一个中声明错误中间件:

app.get('/', (req, res) => ...

app.get('/invite', (req, res, next) => ...

app.get('*', (req, res) => ...

app.use(function(error, req, res, next) => { ... // <= declare error middleware here