Integrating Telebugs with a PHP application

Any PHP application or script can be integrated with Telebugs using the telebugs/telebugs package. In this guide, you will learn how to install and configure Telebugs in your PHP application.

For Laravel applications, please refer to the Laravel integration guide.


Installation

Install the package using Composer by executing:

composer require telebugs/telebugs

Basic example

This is the minimal example that you can use to test Telebugs for PHP with your project:

<?php

require 'vendor/autoload.php';


// Configure the package as early as possible in your application.
Telebugs\configure(function ($config) {
    $config->setApiKey("YOUR_API_KEY");
});

try {
    1 / 0;
} catch (DivisionByZeroError $e) {
    Telebugs\report($e)->wait();
}

echo "An error was sent to Telebugs." .
    "It will appear in your dashboard shortly." .
    "A notification was also sent to your Telegram chat."
?>

Replace YOUR_API_KEY with your actual API key. You can ask @TelebugsBot for your API key or find it in your project's dashboard.

The example above will raise a DivisionByZeroError and send the error to Telebugs.


Configuration

Telebugs for PHP can be configured using the Telebugs\configure method. The method accepts a callback function that takes a single argument: the configuration object.

The configuration object can be used to set the API key and other options. Check the list of all the available options below.

Config options

Option Type Description
setApiKey() String Sets your project's API key
setRootDirectory() String Optional. The working directory of your project. Providing this option helps us filter out repetitive data from backtrace frames.
setEnvironment() String Optional. The environment in which your project is running. This option is used for ignoring errors in certain environments. By default, it is set to an empty string.
setIgnoreEnvironments() Array<String> Optional. A list of environments in which errors should be ignored. By default, it is set to an empty array.
middleware() MiddlewareStack Optional. The middleware stack to be used when reporting an error. You can use this option to add custom middleware to the stack.

Example configuration

Telebugs\configure(function ($config) {
    $config->setApiKey('1:abcdef');
    $config->setRootDirectory('/path/to/your/project');
    $config->setEnvironment('production');
    $config->setIgnoreEnvironments(['development', 'test']);
    $config->middleware()->use(new MyCustomMiddleware());
});

Usage

Telebugs for PHP provides a simple API to report errors to Telebugs.

Reporting an error

To report an error, use the Telebugs\report() method. The method supports the following arguments:

Name Description
$error The error object to report. It must implement the PHP's standard Throwable interface.

Telebugs for PHP reports errors asynchronously by default using Guzzle. This means that the Telebugs\report() method returns a GuzzleHttp\Promise\PromiseInterface object that you can use to track the status of the error report.

You can use all the promise methods provided by guzzle/promises.

In order to actually report the error to Telebugs, you must wait for the error to be sent to Telebugs before the script exits. Otherwise, the error may not be reported.

$promise = Telebugs\report($error);
$promise->wait();

If you want to report multiple errors, you can use the GuzzleHttp\Promise\all() method provided by Guzzle promises:

$promise1 = Telebugs\report($error1);
$promise2 = Telebugs\report($error2);

$promise = GuzzleHttp\Promise\all([$promise1, $promise2]);
$promise->wait();

The wait() method blocks the current thread until the promise is resolved or rejected. The wait time will be equal to the time it takes to send the slowest HTTP request.

Guzzle does not support "fire and forget" requests. You must wait for the promise to be resolved or rejected to ensure that the error is sent to Telebugs.

Using custom middleware

What is a middleware in Telebugs?

Middleware in Telebugs is a class that processes the error report before it is sent to Telebugs. You can use middleware to filter sensitive information, ignore certain errors, or perform other actions on the error report.

All middlewares are attached to the Telebugs\MiddlewareStack object. The middleware stack is processed in the order in which the middleware objects are added to the stack.

You can control the order of middleware in the stack by defining the getWeight() method in your middleware class. The method should return an integer value that represents the weight of the middleware object.

The "heavier" the middleware object, the later it will be processed in the stack.

Built-in middlewares

Telebugs for PHP provides the following built-in middlewares:

Middleware Weight Description
Telebugs\Middleware\IgnoreEnvironments -1000 Ignores errors in certain environments.
Telebugs\Middleware\RootDirectoryFilter -999 Filters the root directory information from the backtrace of the error, so that the backtrace is more readable.
Telebugs\Middleware\ComposerRootFilter -999 Filters out the root path of the packages. It replaces the root path with the package name and version.

How to use custom middlewares

To add custom middleware, use the Telebugs\configure() method with the middleware() option.

To use custom middleware, you need to define a class that inherits from Telebugs\BaseMiddleware and implements the __invoke() method. The __invoke() method is called with the Telebugs\Report object before it is sent to Telebugs.

The following example demonstrates how to add a custom middleware that filters the error message before it is sent to Telebugs:

<?php

class MyCustomMiddleware extends Telebugs\BaseMiddleware
{
  public function __invoke($report): void
  {
    $report->data['errors'][0]['message'] = "[Filtered]";
  }
}

Telebugs\configure(function ($config) {
    $config->middleware()->use(new MyCustomMiddleware());
});

$error = new Exception("Cannot connect to the Docker daemon");
Telebugs\report($error)->wait();

The Telebugs\Report object is passed through each middleware object in the stack.

Changing middleware order

You can change the order of middleware in the stack by defining the getWeight() method in your middleware class. The method should return an integer value that represents the weight of the middleware object.

<?php

class MyCustomMiddleware extends Telebugs\BaseMiddleware
{
  public function __invoke($report): void
  {
    $report->data['errors'][0]['message'] = "[Filtered]";
  }

  public function getWeight(): int
  {
    return 123;
  }
}

Telebugs\configure(function ($config) {
    $config->middleware()->use(new MyCustomMiddleware());
});

$error = new Exception("Cannot connect to the Docker daemon");
Telebugs\report($error)->wait();

The default return value of the getWeight() method is 0. Middleware objects with a lower weight value will be processed first.

Ignoring certain errors

You can use custom middleware to ignore certain errors before they are sent to Telebugs. To ignore an error, you can mark the report as ignored in the middleware's __invoke() method.

The ignored flag is set to false by default. If the flag is set to true, the error report will not be sent to Telebugs:

<?php

class MyCustomMiddleware extends Telebugs\BaseMiddleware
{
  public function __invoke($report): void
  {
    if ($report->data['errors'][0]['message'] === "Cannot connect to the Docker daemon") {
      $report->ignored = true;
    }
  }
}

Telebugs\configure(function ($config) {
    $config->middleware()->use(new MyCustomMiddleware());
});

$error = new Exception("Cannot connect to the Docker daemon");
Telebugs\report($error)->wait();

Ignoring all errors in a certain environment

You can use the setIgnoreEnvironments() option to ignore all errors in certain environments. The setIgnoreEnvironments() option is an array of environment names in which errors should be ignored:

Telebugs\configure(function ($config) {
    $config->setEnvironment("test");
    $config->setIgnoreEnvironments(["development", "test"]);
});

The setIgnoreEnvironments() option takes precedence over custom middleware. If an error is reported in an ignored environment, it will not be sent to Telebugs.


You must set the setEnvironment() option to use the setIgnoreEnvironments() option. Otherwise, the setIgnoreEnvironments() option will have no effect.

Handling the return value

Normally, you would want to know if the error report was sent successfully or if there was an issue with the request. Telebugs for PHP provides a promise object that you can use to track the status of the error report.

The Telebugs.report() method returns a promise that will resolve with the error ID once the error is sent to Telebugs. If the error report fails, the promise will be rejected with an error. Usually, this happens when the API key is invalid or the request to the Telebugs API fails due to network issues, etc.

You can use the promise to handle the error ID and perform additional actions once the error is sent to Telebugs.

Asynchronous error reporting and promise support is powered by the guzzlehttp/guzzle package.

Using "then" and "otherwise"

The then method allows you to define a callback that will be executed once the promise is resolved:

$e = new Exception("Cannot connect to the Docker daemon");
Telebugs\report($e)->then(function($resp) {
  echo "Error {$resp['id']} was sent to Telebugs.";
});

The otherwise method allows you to define a callback that will be executed once the promise is rejected:

$e = new Exception("Cannot connect to the Docker daemon");
Telebugs\report($e)->otherwise(function($reason) {
  echo "You probably forgot to set the API key: {$reason}";
});

Using "wait"

The wait() method blocks the current thread until the promise is resolved or rejected. The wait time will be equal to the time it takes to send the slowest HTTP request.

It is crucial to call the wait() method to ensure that the error is sent to Telebugs before the script exits.

Consult the Guzzle documentation for more information on promises.