Exception handling

In most applications, some errors will get raised that aren't related to possible bugs in your code; they just happen when your app gets into contact with the real world, like when a bot tries to fill in a form.

To avoid these errors from being raised as problems in AppSignal it's possible to add exception handling to your code or even let AppSignal completely ignore certain errors.

Are you calling this instrumentaitons functions outside of a request handler? Please read our Instrumentations Load Instructions documentation to make sure your data gets to AppSignal.

Ignore errors

The AppSignal configuration makes it possible to ignore errors, by providing a list of specific error names in a denylist, AppSignal will not send alerts when these errors are raised.

Record Exceptions

To use the setError and sendError helpers you need to import them from @appsignal/nodejs:

import { setError, sendError } from "@appsignal/nodejs";

Set Error

If you want to catch exceptions in your application to prevent crashes, but still want to track the occurrence you can use setError() to add the error to your applications current active span.

import { setError, sendError } from "@appsignal/nodejs"
 
app.get("/kittens", (req, res) => {
  try {
    fetchAllKittens()
  } catch (err) {
    setError(err)
  }
}

Send Error

The sendError() function can be used to record an incident in a new root span. When using sendError(), the error is sent independently from the current context, so the sample for the request will not be marked as an error. Therefore it can be helpful to provide further context by using non-child span helper functions.

Unlike setError(), the sendError() function can be used in a context where there's no instrumentation such as a one-off script, or job queue.

In the below example setCustomData() is used to add additional data to the error span.

import { setError, sendError } from "@appsignal/nodejs"
 
app.get("/kittens", (req, res) => {
  try {
    fetchAllKittens()
  } catch (err) {
    // oh no, we ran out of kittens!
    // let's keep a note that this happened...
    sendError(err, () => {
      setCustomData({ message: "We ran out of kittens!" })
    })
    // ...and go adopt some more!
    adoptMoreKittens()
  }
}

The exception will be tracked by AppSignal like any other error, and it allows you to provide custom error handling and fallbacks.

Need more help?

Contact us and speak directly with the engineers working on AppSignal. They will help you get set up, tweak your code and make sure you get the most out of using AppSignal.

Contact us

Start a trial - 30 days free

AppSignal is a great way to monitor your Ruby, Elixir & Node.js applications. Works great with Rails, Phoenix, Express and other frameworks, with support for background jobs too. Let's improve your apps together.

Start a trial