StimulusJS - how to ensure controller has all the necessary targets?

Viewed 15

I'm trying to find a way to make my Stimulus controller more robust and maintainable by checking that all the required targets are present. If something is missing, I would like it to fail fast and loud.

Below is what I'm using so far:

export default class extends Controller {
  static targets = ['name'];

  connect() {
    if (!that.hasNameTarget) {
      throw new Error('expected to find name target');
    }
  }
}

Perhaps someone knows of a more idiomatic/clean solution?

1 Answers

Option 1 - use the Stimulus debugger tooling

Stimulus has a debug mode that logs out info/warnings etc for Stimulus controllers. You can enable this by stimulus.debug = true;

You can call this in your own controllers via this.application.logDebugActivity() - see https://github.com/hotwired/stimulus/blob/main/src/core/application.ts#L95

export default class extends Controller {
  static targets = ['name'];

  connect() {
    if (!that.hasNameTarget) {
      this.logDebugActivity(this.identifier, 'error', { message: 'target missing'});
      throw new Error('expected to find name target');
    }
  }
}

Option 2 - Use the window.onerror callback

If you keep your current code where an error is thrown, Stimulus will not 'break' anything where possible as all calls within Stimulus use try/catch.

However, you can ensure that your error does something 'loud' by creating a onerror function.

See docs - https://stimulus.hotwired.dev/handbook/installing#error-handling

See an example where this can be used for something like Sentry https://blog.sentry.io/2016/01/04/client-javascript-reporting-window-onerror

You could also just be really loud and block the UI with something similar to this.

window.onerror = (message, url, lineNo, columnNo, error) => {
   document.body.style.backgroundColor = 'red';
   window.alert(message);
}

Reminders

Remember to only enable these debugging features in local development, you can do this with something like Webpack environment variables but this will be different depending on your tooling.

In production though you may want to push your onerror calls to whatever logging infrastructure you have.

stimulus.debug mode is quite 'noisy' and may be too much information, depending on your set up.

Related