Send PHP errors to Telegram with lograh-php package
Tags: php, tutorial, beginners, webdev
Published: 2024-03-20 14:24:41


## Introduction

### Error handling in PHP
Error handling is one of the critical aspects of any PHP application. When unexpected situations occur during program execution, proper error management ensures that the application can easily handle these scenarios without crashing or producing undesirable outcomes.

In PHP, the ‘try’ and ‘catch’ constructs are fundamental components of the language’s exception handling mechanism. These basically tells the source code to ‘try’ and execute a block of code and if an exception occurs, it ‘catch’es it and any action can be taken in the ‘catch’ block without stopping the running process.

Here’s a basic example of a try-catch block in action.

```php
<?php
 try {
  // run piece of code that may throw an exception
 } catch (\Throwable $exception) {
  // log or process the exception
  echo “Caught an exception: “ . $exception->getMessage();
 }
 // do some other things
```
In this example, we have a ‘try’ block that might throw an exception and if one were to occur, it is caught in the corresponding ‘catch’ block and you can access any information about the exception from the ‘$exception’ variable.

### The lograh-php package
Let’s say we have a scenario where you have a critical process running in your PHP project and you would like to be notified outside of your app as soon as an exception occurs. There are a lot of packages and third-party tools out there that can be used to implement, but a host of them are either too complicated to set up, have a lot of dependencies (which can impact performance) or cost you to use.

The lograh-php package is a very light-weight solution for this as it easily utilizes Telegram’s popular Bots API, allowing you to send information about these exceptions directly to any dedicated chat, group or channel on your Telegram account.

---
## Setup
Before you can use this package, you need a Telegram Bot setup on your account. What we need here is the API Key generated after creating your Bot and your chat, group or channel ID.

### Obtain your bot token
Obtaining your Bot token is a pretty straightforward process in the steps listed below.

Follow this link [https://t.me/botfather](https://t.me/botfather) to interact with the BotFather to generate a new Telegram bot.

Once it opens up, if not already selected, type in the command ‘/newbot’ in the message box or select the option from the side menu and follow through with the prompts as shown in the screenshot below.
![screenshot of how to create your Telegram bot and get generate an API token](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3m3q0yltlh22mmqauwip.png)

Copy the token and keep in a secure place.
![screenshot of the section with the API token](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/59bzd2vwenqdm2dubary.png)

Then click on your bot link.
![screenshot of the section with the Telegram bot link](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pcusqs80jku01v0q1glo.png)

This takes you to a chat window with your window, then you click “Start” button at the bottom of the screen or enter the “/start” command in the message box.

### Get your chat ID
Your chat ID is used to identify the chat that the logs would be sent to. This could be your direct inbox, a public/private that you have admin access to. In this scenario, we will be sending the logs directly to your chat.

Follow this link [https://t.me/userinfobot](https://t.me/userinfobot) to interact with the “userinfobot” to display your user info when you forward a message to it.

Click the “start” button on the bottom of the screen or type in the command “/start”.

![screenshot of user details after using the start prompt](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/trac359a12i3sa0j7cym.png)

This should show your user details.

Copy your ID and also keep in a secure place for later.

### Include the lograh-php package
If your PHP project is setup with composer, you can easily import the package by running the command below
```bash
composer require codelikesuraj/lograh-php
```
![screenshot of terminal process after adding the lograh-php package to the package](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g3a7a99cp0hsh9epnzp5.png)
Or you can copy/clone the project from github, https://github.com/codelikesuraj/lograh-php.

---
## Usage
We are going to be using a skeleton project I created specifically for this tutorial, you can check out the source-code here https://github.com/codelikesuraj/lograh-tut.

Create an index.php file in the root of the project
```bash
touch index.php
```
Inside the index.php file, initialize an instance of the LograhPHP\Logger class with your project name, bot token and chat ID.
```php
<?php
require_once("vendor/autoload.php");

$logger = new Codelikesuraj\LograhPHP\Logger(
    appName: "Lograh Tutorial",
    botToken: "api_key_generated_from_your_telegram_bot",
    chatId: "id_of_your_telegram_chat_or_channel_or_group"
);
...
```
Then add this simple try-catch block just below it.
```php
...
try {
    throw new \Exception("I am an error from Lograh-tut");
} catch (\Throwable $exception) {
    // send exception to Telegram using any
    // of the following methods
    $logger->reportAsText($exception);
}
```
Now run the code and you should receive a message on your telegram that looks something like this.
```bash
php index.php
```
![screenshot of message when an exception is caught and the 'reportAsText' method is used](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wn1xcnx6hd35h68g11a5.png)
Also, for a JSON style message, you can use either use the ‘reportAsJson()’ or ‘reportAsJsonWithStackTrace()’ method which as the name suggests sends the report as a JSON without and with the stack trace respectively.

Here’s a sample of what those implementations might look like.
```php
...
$logger->reportAsJson($exception);
...
```
![screenshot of message when 'reportAsJson' method is used](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jus3m0u5lhv1ioar61br.png)
```php
...
$logger->reportAsJsonWithStackTrace($exception);
...
```
![screenshot of message when 'reportAsJsonWithStackTrace' method is used](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/le7g67xbgfsz40xgl5qd.png)