Error catching

In this guide we will see how you can catch errors and send them to the Application Monitoring / Error Tracking Software you want.

TIP

In this example we will use SentryError catching - 图1 (opens new window).

Create a middleware

A middleware will be used in order to catch the errors which will then be sent to Sentry.

  • Create a ./middlewares/sentry/index.js file.

Path — ./middlewares/sentry/index.js

  1. module.exports = strapi => {
  2. return {
  3. initialize() {
  4. strapi.app.use(async (ctx, next) => {
  5. await next();
  6. });
  7. },
  8. };
  9. };

Handle errors

Here is the Node.js client documentationError catching - 图2 (opens new window).

Install it with yarn add @sentry/node or npm install @sentry/node --save.

  • Now add the logic that will catch errors.

Path — ./middlewares/sentry/index.js

  1. const Sentry = require('@sentry/node');
  2. Sentry.init({
  3. dsn: 'https://<key>@sentry.io/<project>',
  4. environment: strapi.config.environment,
  5. });
  6. module.exports = strapi => {
  7. return {
  8. initialize() {
  9. strapi.app.use(async (ctx, next) => {
  10. try {
  11. await next();
  12. } catch (error) {
  13. Sentry.captureException(error);
  14. throw error;
  15. }
  16. });
  17. },
  18. };
  19. };

WARNING

It’s important to call throw(error); to avoid stopping the middleware stack. If you don’t re-throw the error, it won’t be handled by the Strapi’s error formatter and the api will never respond to the client.

Configure the middleware

To ensure that your middleware catches all errors including those in other middleware, it needs to be added at the beginning of the stack but after the boom middleware.

After, the sentry middleware captures and rethrows the error, boom will return an appropriate HTTP response to the client.

Path — ./config/middleware.js

  1. module.exports = {
  2. load: {
  3. before: ['boom', 'sentry', ...],
  4. ...
  5. },
  6. };

And finally you have to enable the middleware.

Path — ./config/middleware.js

  1. module.exports = {
  2. settings: {
  3. sentry: {
  4. enabled: true,
  5. },
  6. },
  7. };