Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sentry doesn't catch all errors in a nodejs environment

Tags:

node.js

sentry

I am trying to deploy a sentry installation for catching the errors in my app and somehow I don't really understand how to do that.

I have this sample app:

const express = require('express');
const app = express();
var Raven = require('raven');
Raven.config('http://[email protected]/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 logs perfectly the errors on the / route but nothing on the /KO route. I want to make it log all the errors which might appear in the node console without using throw error.

How do I do that?

like image 996
Bogdan Avatar asked Sep 12 '25 04:09

Bogdan


2 Answers

Place the app.use lines after all routes, particularly the onError handler. Node's native error handling may be catching it before Sentry's.

const express = require('express');
const app = express();
var Raven = require('raven');
Raven.config('http://[email protected]/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');
});

Disclosure: I work at Sentry, but I don't maintain our our Node SDK. Please open an issue in the node repo if you'd like a more in-depth answer.

like image 65
ehfeng Avatar answered Sep 13 '25 20:09

ehfeng


My mistake was not realizing Sentry doesn't catch 4xx errors by default, see 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.

If you're certain you want to catch all 400/500 errors, do:

app.use(Sentry.Handlers.errorHandler({
  shouldHandleError: error => error.status >= 400,
}));
like image 20
Lucia Avatar answered Sep 13 '25 21:09

Lucia