Error handling

This guide explains how to handle errors in plugins.

Provide usable defaults

Allow the user to learn your plugin in small steps. Provide a useful default configuration so that:

  • The user can get started right away.
  • You can avoid unnecessary error messages.

For example, by selecting the first field of an expected type, the panel can display a visualization without any user configuration. If a user explicitly selects a field, then use that one. Otherwise, default to the first field of type string:

  1. const numberField = frame.fields.find((field) =>
  2. options.numberFieldName ? field.name === options.numberFieldName : field.type === FieldType.number
  3. );

Display error messages

To display an error message to the user, throw an Error with the message you want to display:

  1. throw new Error('An error occurred');

Grafana displays the error message in the top-left corner of the panel.

Error handling - 图1 Avoid displaying overly-technical error messages to the user. If you want to let technical users report an error, consider logging it instead.

  1. try {
  2. failingFunction();
  3. } catch (err) {
  4. console.error(err);
  5. throw new Error('Something went wrong');
  6. }

Note: Grafana displays the exception message in the UI as written, so we recommend using grammatically correct sentences. For more information, refer to the Documentation style guide.

Here are some examples of situations where you might want to display an error to the user.

Invalid query response

Users have full freedom when they create data source queries for panels. If your panel plugin requires a specific format for the query response, then use the panel canvas to guide the user.

  1. if (!numberField) {
  2. throw new Error('Query result is missing a number field');
  3. }
  4. if (frame.length === 0) {
  5. throw new Error('Query returned an empty result');
  6. }