Best Practices for using Sentry with Node.js
I’ve used Sentry since 2010, way back when it still had Starcraft inspired logos and when you had to host it yourself. Now Raven has clients for all the popular languages including Node.js and hosted Sentry is the de facto way to get started. I’ve spent the last 15 months working on a Node.js codebase at Mixmax. Here are some of the best practices I’ve picked up for identifying code bugs with Sentry and Raven.
Use the same Raven configuration wrapper for each project
Raven automatically configures itself from environment variables, but a wrapper module will come in handy to implement the rest of the tips in this post.
https://gist.github.com/andrewtamura/331982a57775eb90012c071979a89952
Monkey patch Raven to log to console for local development
It’s cumbersome for all the engineers on your team to use the Sentry web interface when developing locally. Even worse would be to have an isLocal condition everytime you log an exception with Raven. Instead of poluting your Sentry with useless artifacts from local development just leave the SENTRY_DSN environment variable unset for local development.
Raven’s dataCallback will fire even if Raven isn’t configured with a Sentry DSN. Unfortunately Raven doesn’t pass back the original Error object to the dataCallback. Monkey patching the captureException function is one way to print the original exception. Note: this monkey patch won’t be necessary once raven-node integrates with console.error
https://gist.github.com/andrewtamura/61d32b1b1ea9e98c5e15cb833243d755
Use the culprit property to identify the same Errors from different code paths
It is very common to use a module in multiple code paths. Unfortunately, the default Sentry view doesn’t expose the different code paths. In order to see which codepaths are affected, you need to go into the Sentry event and view the stack trace. Consider the given code
https://gist.github.com/andrewtamura/8a1e70792ecdbd54e07d53ce430823a9
Functions foo and bar both call the thowsException function. However in Sentry it isn’t obvious which code paths have thrown this exception.
Set the culprit property to a unique string when logging exceptions from shared modules. This will help identify which line of code the error was caused by.
https://gist.github.com/andrewtamura/971416c485d0cd2311382c9c38571d3b
Add server context as Sentry Tags
Your web application is probably deployed across many servers. Sometimes the problem isn’t your code, but rather some property of your server. Some third party API’s will rate limit or blacklist clients based on IP addresses. Adding the public IP address (if applicable) and the server ID may help identify exceptions that are caused by some property of your server.
https://gist.github.com/andrewtamura/830541e1fea55f0c0998a7b146a5e941
How do you use Raven in your node.js codebases? Comment on Hacker News.
Andrew Tamura