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?
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.
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,
}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With