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
::: note
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-10-24 15:08:42 +02:00
Here is the [Node.js client documentation ](https://docs.sentry.io/platforms/node/ )
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 ');
Sentry.init({ dsn: 'https://< key > @sentry .io/< project > ' });
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
**Path —** `./config/middleware.json`
```json
{
...
"after": [
"parser",
"router",
"sentry"
]
}
}
```
2019-10-24 15:08:42 +02:00
And finally you have to enable the middleware.
2019-10-23 14:36:51 +02:00
**Path —** `./config/environments/**/middleware.json`
```json
{
"sentry": {
"enabled": true
}
}
```