This article describes how to capture exceptions thrown in Symfony console application in Sentry. The fundamental solution is posted on StackOverflow. In here I describe it in more detail.

To capture exceptions thrown in Symfony console application in Sentry, the Symfony Event Dispatcher is used.

composer require symfony/event-dispatcher

The Event Dispatcher provides a console.error event. A listener will be called when an exception is thrown. The listener will then capture the exception in Sentry.

use Symfony\Component\EventDispatcher\EventDispatcher;

// Ensure Sentry is initialized

$dispatcher = new EventDispatcher();
$dispatcher->addListener(
    ConsoleEvents::ERROR,
    static function (ConsoleErrorEvent $event) {
        captureException($event->getError());
    }
);

The dispatcher is then passed to the Application class.

use Symfony\Component\Console\Application;

$application = new Application('My Application', '1.0.0');
$application->setDispatcher($dispatcher);