JSON响应并在Express中调用next()

3 node.js express

是否有可能使用Express 4向前端发送JSON响应,指示存在错误,以及在Express中间件内调用next(err),以便服务器也可以处理错误?或者这些电话完全相互排斥?

我目前的假设是你可以这样做:

app.get('/', function(req, res, next) {
  res.json({ error : true });
});
Run Code Online (Sandbox Code Playgroud)

你可以这样做:

app.get('/', function(req, res, next) {
  next(new Error('here goes the error message');
});
Run Code Online (Sandbox Code Playgroud)

但你不能这样做

app.get('/', function(req, res, next) {
  res.json({ error : true });
  next(new Error('here goes the error message');
});
Run Code Online (Sandbox Code Playgroud)

你不能这样做:

app.get('/', function(req, res, next) {
  next(new Error('here goes the error message');
  res.json({ error : true });
});
Run Code Online (Sandbox Code Playgroud)

rob*_*lep 6

它们不是相互排斥的.例如(代替中间件我使用路由处理程序来演示,但两者的原理相同):

app.get('/', function(req, res, next) {
  res.json({ error : true });
  next(new Error('something happened'));
});

app.get('/another', function(req, res, next) {
  next(new Error('something happened'));
});

app.use(function(err, req, res, next) {
  console.error(err);
  if (! res.headersSent) {
    res.send(500);
  }
});
Run Code Online (Sandbox Code Playgroud)

您可以检res.headersSent入错误处理程序以确保发送响应(如果没有,错误处理程序应该自己发送一个).