Search code examples
phplaravellaravel-4exceptionraygun.io

Custom error and exception handler for Artisan command


I'm trying to send errors and exceptions to raygun.io from a Laravel 4 artisan command, but Laravel appears to have it's own exception handler in place.

Is there a way for me to specify a custom method in my Command? Currently, I'm trying to specify a custom handler for errors and exceptions as follows:

<?php
class ParseCommand extends Command
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'my:parse';

    protected $descriptino = '...';

    protected $raygun = null;

    /**
     * __construct
     */
    public function __construct()
    {
        parent::__construct();

        // Setup custom error and exception handlers
        $raygun_api_key = \Config::get('tms.raygun_api_key');
        $this->raygun = new RaygunClient("MUzf+furi8E9tffcHAaJVw==");
        set_exception_handler([$this, 'exceptionHandler']);
        set_error_handler([$this, 'errorHandler']);
    }

    /**
     * Custom exception handler.
     *
     * @param $exception
     */
    public function exceptionHandler($exception)
    {
        $this->raygun->SendException($exception);
    }

    /**
     * Custom error handler.
     *
     * @param $errno
     * @param $errstr
     * @param $errfile
     * @param $errline
     */
    public function errorHandler($errno, $errstr, $errfile, $errline)
    {
        $this->raygun->SendError($errno, $errstr, $errfile, $errline);
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function fire()
    {
        $start_time = microtime(true);
        throw new \Exception("Oopsie!");

        // Omitted for brevity...
    }
}

Off course the handlers never execute, as Artisan is grabbing them with it's own custom implementation.


Solution

  • The files in the folder app/start are only executed while booting the Laravel framework when the according environment is run. This means that app/start/local.php is run when the environment is equal to local and app/start/staging.php is run when the environment is equal to staging. Also the app/start/global.php file is run every time and app/start/artisan.php is run on every artisan execution.

    From the documentation: http://laravel.com/docs/errors place the handler

    App::error(function(Exception $exception)
    {
        Log::error($exception);
    });
    

    in app/start/artisan for your artisan-only exception handlers.