Skip to content

Instantly share code, notes, and snippets.

@mauriciovillalobos
Created December 8, 2016 21:33
Show Gist options
  • Save mauriciovillalobos/01a97f9ee6179ad70b17d54f37cc5010 to your computer and use it in GitHub Desktop.
Save mauriciovillalobos/01a97f9ee6179ad70b17d54f37cc5010 to your computer and use it in GitHub Desktop.
Airbrake integration for CakePHP 3.x - To keep the CakePHP error flow.
<?php
// ...
use App\Error\AirbrakeHandler;
// ...
/**
* Register application error and exception handlers.
*/
$isCli = PHP_SAPI === 'cli';
if ($isCli) {
(new ConsoleErrorHandler(Configure::read('Error')))->register();
} else {
(new AirbrakeHandler(Configure::read('Error')))->register();
}
<?php
namespace App\Error;
use Cake\Core\Configure;
use Cake\Error\ErrorHandler;
use Airbrake\Notifier as AirbrakeNotifier;
use Airbrake\ErrorHandler as AirbrakeErrorHandler;
use Airbrake\Instance as AirbrakeInstance;
/**
* Airbrake Handler, this class allows for an error or exception to be sent to airbrake,
* while also allowing the normal CakePHP error flow
*/
class AirbrakeHandler extends ErrorHandler
{
protected $_airbrakeHandler;
/**
* Constructor
*
* @param array $options The options for error handling.
*/
public function __construct($options = [])
{
$this->setupAirbrake();
$options['debug'] = Configure::read('debug');
parent::__construct($options);
}
/**
* Setup airbrake instance and register shutdown function
*/
protected function setupAirbrake()
{
// Create new Notifier instance.
$notifier = new Airbrake\Notifier([
'projectId' => 12345, // FIX ME
'projectKey' => 'abcdefg' // FIX ME
]);
// Set global notifier instance.
AirbrakeInstance::set($notifier);
// Setup the Airbrake Error Handler.
$this->_airbrakeHandler = new AirbrakeErrorHandler($notifier);
// Register shutdown function manually, since we're not calling $handler->register();
register_shutdown_function([$this->_airbrakeHandler, 'onShutdown']);
}
/**
* {@inheritDoc}
*/
public function handleError($code, $description, $file = null, $line = null, $context = null)
{
$this->_airbrakeHandler->onError($code, $description, $file, $line);
return parent::handleError($code, $description, $file, $line, $context);
}
/**
* {@inheritDoc}
*/
public function wrapAndHandleException($exception)
{
$this->_airbrakeHandler->onException($exception);
parent::wrapAndHandleException($exception);
}
}
@ethanpooley
Copy link

ethanpooley commented Jan 30, 2017

I had to use AirbrakeNotifier rather than Airbrake\Notifier on line 38.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment