如何处理nginx后面的nodejs中的错误?

Eri*_*rik 1 error-handling nginx node.js

我有在Nginx后面处理的nodejs / expressjs应用程序。在expressjs应用程序中,我具有以下错误处理中间件:

app.use(function(req, res, next){
  res.status(404);

  // respond with json
  if (req.accepts('json')) {
    res.send({ error: 'Not found' });
    return;
  }

  // respond with html page
  if (req.accepts('html')) {
    res.render('404', { url: req.url });
    return;
  }

  // default to plain-text. send()
  res.type('txt').send('Not found');
});

app.use(function(err, req, res, next){
  res.status(err.status || 500);

  // respond with json      
  if (req.accepts('json')) {
    res.send({ error: 'Not found' });
    return;
  }

  // respond with html page
  if (req.accepts('html')) {
    res.render('500', { error: err });
    return;
  }

  res.type('txt').send('Internal error');
});
Run Code Online (Sandbox Code Playgroud)

同样在nginx中,我有以下配置用于错误处理:

error_page 404 /404.html;
location = /404.html {
  internal; 
  root /path/to/static/html/;
}

error_page 400 500 502 503 504 /50x.html;         
location /50x.html {                 
  internal;                 
  root /path/to/static/html/;         
}
Run Code Online (Sandbox Code Playgroud)

当我尝试通过nodejs发送一些错误时,如下所示

res.status(500).json({error: 'Something happened'});
Run Code Online (Sandbox Code Playgroud)

此错误处理nginx,我得到完整的html错误页面响应,而不是json响应。我认为这是由于以下nginx配置:

error_page 400 500 502 503 504 /50x.html;         
location /50x.html {                 
  internal;                 
  root /path/to/static/html/;         
}
Run Code Online (Sandbox Code Playgroud)

我如何设置nginx来仅处理nodejs服务器未处理的错误?

谢谢。

Ale*_*Ten 6

您正在使用proxy_intercept_errors on指令。为了仅拦截某些错误代码,只需将error_page指令添加到具有代理的位置。否则,它们将被继承。

在这里,我们仅拦截400和502个错误,其他所有错误都会传递给客户端。

location / {
    proxy_pass http://myapp_upstream;
    proxy_intercept_errors on;
    error_page 400 502 /50x.html;
}
Run Code Online (Sandbox Code Playgroud)

  • 是否可以检查响应是否为 json 然后使用节点 js 处理错误,但如果 html 然后使用 nginx 处理? (2认同)