|
| 1 | +# Use case |
| 2 | +Once your Express application is deployed, it is important to get notified of any errors in real-time. While there are many advanced solutions for this task already, this utility middleware focuses on being minimalistic, easy setup and of course the cosy Telegram :). |
| 3 | + |
| 4 | +# Setup |
| 5 | +1. Write to [BotFather](https://t.me/botfather), give it a command `/newbot`, answer the questions, and it will give you a secret token (we call this `botToken`). |
| 6 | +2. Create a channel, give it a username, and add the bot you have just created to this channel. |
| 7 | +3. Inside of your project directory, run `npm install --save express-notify-telegram`. Afterwards, run `npx express-notify-telegram`, this CLI will ask you `botToken` and channel's username you created in the previous step and give you the channel's `chatId`. |
| 8 | +4. Finally, in your application, add the following: |
| 9 | +```js |
| 10 | + const express = require('express'); |
| 11 | + const telegramMiddleware = require('express-notify-telegram'); |
| 12 | + |
| 13 | + const app = express(); |
| 14 | + |
| 15 | + app.use(telegramMiddleware({ |
| 16 | + botToken: '<your botToken from above>', |
| 17 | + chatId: '<the chatId you got from the CLI>' |
| 18 | + })); |
| 19 | + |
| 20 | + // One of your endpoints |
| 21 | + app.get('/resource', (req, res) => { |
| 22 | + try { |
| 23 | + // Some code that throws error |
| 24 | + } catch(e) { |
| 25 | + // This will fire a notification, as it has an erroneous 500 statusCode. |
| 26 | + res.status(500).json({ /* whatever */ }); |
| 27 | + |
| 28 | + // If you want a custom error message in the notification, add the following: |
| 29 | + req.errorMessage = 'My custom error message'; |
| 30 | + } |
| 31 | + }); |
| 32 | + |
| 33 | +``` |
0 commit comments