Search code examples
phpapislimslim-2

How I can override Slim's version 2 default error handling function


How can I override Slim's version 2 default error handling? I don't want my application to crash everytime I get a warning message. Basically I want to override function handleErrors() from \Slim\Slim class.

I looked into how I might override this behavior, but because it's called as:

set_error_handler(array('\Slim\Slim', 'handleErrors')); in Sim's run() method, I had to edit the Slim source code myself. I changed the above to: set_error_handler(array(get_class($this), 'handleErrors')); Then I extended Slim with different behavior for handleErrors() and instantiated my custom class instead of Slim. Its works fine But I don't want to touch Slim's core class. Code FYI

public static function handleErrors($errno, $errstr = '', $errfile = '', $errline = '')
{
    if (error_reporting() & $errno) {
        //Custom Block start here
        $search = 'Use of undefined constant';
        if(preg_match("/{$search}/i", $errstr)) {
            return true; //If undefined constant warning came will not throw exception
        }
        //Custom Block stop here
        throw new \ErrorException($errstr, $errno, 0, $errfile, $errline);
    }

    return true;
}

Please help with the correct way to override handleErrors()


Solution

  • Extend the class and override the respective methods handleErrors() and run().

    class Core_Slim_Slim extends \Slim\Slim
    {
    public static function handleErrors($errno, $errstr = '', $errfile = '', $errline = '')
        {
            //Do whatever you want...
        }
    
    public function run()
        {
            set_error_handler(array('Core_Slim_Slim', 'handleErrors'));
        }
    
    }
    

    instantiate New custom slim class and call its Run method as bellow.

    $app = new Core_Slim_Slim();
    $app->run();
    

    Thanks Everyone for your Reply :)