You want to catch errors pertaining to Stimulus (
targets not being accessible etc.) as well as application errors within your controllers and send them to an error tracking service of your choice (e.g. Sentry, Honeybadger etc.).
First define a global Application Controller that your Stimulus controllers will inherit from.
Within this ApplicationController define a new
handleError function. Here this function creates a small context object with the id of the current user (you can pass all context information that can help you debug: environment, subscription status, etc).
Stimulus includes a largely undocumented error handler (see links below). By default, this error handle catches all Stimulus internal errors and output a prettified
handleError function we can call this
application.handleError with our custom context to have a single function being responsible to manage and report errors.
In your controllers now you can catch errors and pass them to
this.handleError for reporting.
Here is an example to configure Sentry for reporting Stimulus errors :
This new instrumented handler will now send global errors to Sentry. The example above shows how you can furthermore use this function to catch errors in our own application code in
The rationale behind all this, is to have a single error handler for all errors within a Stimulus Controller. Whether they are Stimulus or application errors they all go through the same path. Once this unique handler is in place it is easy to add context to the error message and dispatch errors to various reporting systems such as Sentry, Honeybadger or others.