2019-10-24 15:08:42 +02:00
# Error catching
2019-10-23 14:36:51 +02:00
2019-10-24 15:08:42 +02:00
In this guide we will see how you can catch errors and send them to the Application Monitoring / Error Tracking Software you want.
2019-10-23 14:36:51 +02:00
2019-11-07 12:05:39 +01:00
::: tip
2019-10-23 14:36:51 +02:00
In this example we will use [Sentry ](https://sentry.io ).
:::
## Create a middleware
2019-10-24 15:08:42 +02:00
A [middleware ](../concepts/middlewares.md ) will be used in order to catch the errors which will then be sent to Sentry.
2019-10-23 14:36:51 +02:00
- Create a `./middlewares/sentry/index.js` file.
**Path —** `./middlewares/sentry/index.js`
```js
module.exports = strapi => {
return {
initialize() {
strapi.app.use(async (ctx, next) => {
await next();
});
},
};
};
```
## Handle errors
2019-11-06 09:26:25 +01:00
Here is the [Node.js client documentation ](https://docs.sentry.io/platforms/node/ ).
Install it with `yarn add @sentry/node` or `npm install @sentry/node --save` .
2019-10-23 14:36:51 +02:00
- Now add the logic that will catch errors.
**Path —** `./middlewares/sentry/index.js`
```js
2019-10-24 15:08:42 +02:00
const Sentry = require('@sentry/node ');
2019-11-05 11:16:20 +01:00
Sentry.init({
dsn: 'https://< key > @sentry .io/< project > ',
2019-11-06 09:26:25 +01:00
environment: strapi.config.environment,
2019-11-05 11:16:20 +01:00
});
2019-10-23 14:36:51 +02:00
module.exports = strapi => {
return {
initialize() {
strapi.app.use(async (ctx, next) => {
try {
await next();
} catch (error) {
2019-10-24 15:08:42 +02:00
Sentry.captureException(error);
2019-10-23 14:36:51 +02:00
throw error;
}
});
},
};
};
```
::: warning
2019-10-24 15:08:42 +02:00
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.
2019-10-23 14:36:51 +02:00
:::
## Configure the middleware
2019-10-24 15:08:42 +02:00
Make sure your middleware is added at the end of the middleware stack.
2019-10-23 14:36:51 +02:00
2020-04-10 15:47:47 +02:00
**Path —** `./config/middleware.js`
```js
module.exports = {
load: {
after: ['parser', 'router', 'sentry'],
},
};
2019-10-23 14:36:51 +02:00
```
2019-10-24 15:08:42 +02:00
And finally you have to enable the middleware.
2019-10-23 14:36:51 +02:00
2020-04-10 15:47:47 +02:00
**Path —** `./config/middleware.js`
2019-10-23 14:36:51 +02:00
2020-04-10 15:47:47 +02:00
```js
module.exports = {
settings: {
sentry: {
enabled: true,
},
},
};
2019-10-23 14:36:51 +02:00
```