Sentry 不会捕获 nodejs 环境中的所有错误

Sentry doesn't catch all errors in a nodejs environment

我正在尝试部署哨兵安装以捕获我的应用程序中的错误,但不知何故我真的不明白该怎么做。

我有这个示例应用程序:

const express = require('express');
const app = express();
var Raven = require('raven');
Raven.config('http://6c4b87dasdasdf3ecca9@logs.ekaf.com/7').install();
app.use(Raven.requestHandler());

app.get('/', function mainHandler(req, res) {
        throw new Error('Broke!');
});
app.use(Raven.errorHandler());
app.use(function onError(err, req, res, next) {
    res.statusCode = 500;
    res.end(res.sentry + '\n');
});

const PORT = process.env.PORT || 443;

app.listen(PORT, () => {
  console.log(`Server is listening on port ${PORT}`);
});

app.get('/OK', (req, res, next) => {
  res.send('route OK');
});

app.get('/KO', (req, res, next) => {
  res.send(blabla);
});

Sentry 完美地记录了 / 路由上的错误,但 /KO 路由上没有任何错误。我想让它在不使用 throw error.

的情况下记录节点控制台中可能出现的所有错误

我该怎么做?

app.use 行放在所有路由之后,尤其是 onError 处理程序。 Node 的本机错误处理可能会在 Sentry 之前捕获它。

const express = require('express');
const app = express();
var Raven = require('raven');
Raven.config('http://6c4b87dasdasdf3ecca9@logs.ekaf.com/7').install();
app.use(Raven.requestHandler());

app.get('/', function mainHandler(req, res) {
        throw new Error('Broke!');
});
const PORT = process.env.PORT || 443;

app.listen(PORT, () => {
  console.log(`Server is listening on port ${PORT}`);
});

app.get('/OK', (req, res, next) => {
  res.send('route OK');
});

app.get('/KO', (req, res, next) => {
  res.send(blabla);
});

app.use(Raven.errorHandler());
app.use(function onError(err, req, res, next) {
    res.statusCode = 500;
    res.end(res.sentry + '\n');
});

披露:我在 Sentry 工作,但我不维护我们的 Node SDK。如果您想要更深入的答案,请在节点回购中打开一个问题。

我的错误是没有意识到默认情况下 Sentry 不会捕获 4xx 错误,请参阅 here:

By default, errorHandler will capture only errors with a status code of 500 or higher. If you want to change it, provide it with the shouldHandleError callback, which accepts middleware errors as its argument and decides, whether an error should be sent or not, by returning an appropriate boolean value.

要捕获所有 400/500 错误,请执行:

app.use(Sentry.Handlers.errorHandler({
  shouldHandleError: error => error.status >= 400,
}));