Accessing getLastEventId() from CakePHP

I don’t have much experience with CakePHP but after some googling I think I know what is happening.

The Exception you are throwing in the controller is not actually caught by Sentry and should also not popup in your Sentry feed, this is because Cake is capturing the exception thus Sentry never sees it because Cake handled it. The reason when you add use Sentry; to the template you do get an ID is because an warning is generated and Sentry does see that (and reports is as ErrorException) which is the ID you are getting.

If the actual exception does show up in Sentry you are sending the event maybe after Cake renders the exception page thus not having the event ID available when you are trying to display it.


I replaced the error handler code in config/bootstrap.php with the following to get it to work correctly and be able to use \Sentry\State\Hub::getCurrent()->getLastEventId() in the errror500.ctp template file:

/*
 * Register application error and exception handlers.
 */
$isCli = PHP_SAPI === 'cli';
if ($isCli) {
    (new ConsoleErrorHandler(Configure::read('Error')))->register();
} else {
    \Sentry\init(['dsn' => 'YOUR_DSN' ]);

    class SentryErrorHandler extends ErrorHandler {
        public function handleException(Exception $exception)
        {
            \Sentry\captureException($exception);

            parent::handleException($exception);
        }
    }
    class SentryErrorHandlerMiddleware extends \Cake\Error\Middleware\ErrorHandlerMiddleware {
        public function handleException($exception, $request, $response)
        {
            \Sentry\captureException($exception);

            return parent::handleException($exception, $request, $response);
        }
    }

    (new SentryErrorHandler(Configure::read('Error')))->register();

    $appClass = Configure::read('App.namespace') . '\Application';
    if (class_exists($appClass)) {
        \Cake\Event\EventManager::instance()->on('Server.buildMiddleware', function ($event, $queue) {
            /* @var \Cake\Http\MiddlewareQueue $queue */
            $middleware = new SentryErrorHandlerMiddleware();
            try {
                $queue->insertAfter(\Cake\Error\Middleware\ErrorHandlerMiddleware::class, $middleware);
            } catch (LogicException $e) {
                $queue->prepend($middleware);
            }
        });
    }
}

It would be helpful to know how you implemented the PHP SDK in you application so we can see what might be happening!