Search code examples
node.jssentry

Sentry doesn't catch all errors in a nodejs environment


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://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 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?


Solution

  • 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://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');
    });
    

    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.