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

285 views Asked by At

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()

2

There are 2 answers

0
user2800404 On BEST ANSWER

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 :)

1
Ebski On

I handle it in my index.php the following way

// Prepare the Slim application container
$container = new Container();

// Set up error handlers
$container['errorHandler'] = function () {
    return new ErrorHandler();
};
$container['phpErrorHandler'] = function () {
    return new ErrorHandler();
};
$container['notAllowedHandler'] = function () {
    return new NotAllowedHandler();
};
$container['notFoundHandler'] = function () {
    return new NotFoundHandler();
};
// Set up the container
$app = new App($container);

$app->run();

It's also possible to overwrite both the default slim request and response this way