Search code examples
silverstripe-4

Calling the default exceptionHandler equivalent in SilverStripe 4


I've searched through the documentation and the API for SilverStripe 4 but I'm having trouble using the appropriate class to call the default exception handler.

How it worked before SilverStripe 4 within my Page.php controller's init()

    parent::init();

    set_exception_handler(function($exception) {
        if( get_class($exception) == 'CustomException' ) {
            Controller::curr()->handleCustomException($exception);
        }
        return exceptionHandler($exception);
    });

How I expect it to work with SilverStripe 4

    parent::init();

    set_exception_handler(function($exception) {
        if( get_class($exception) == 'CustomException' ) {
            Controller::curr()->handleCustomException($exception);
        }
        return <SomeMonologClass>::handleException($exception);
    });

I'm aware of SilverStripe 4 now using Monolog and I've come across the handleException function which I believe is what I need to call instead of exceptionHandler($exception).

Any advice would be much appreciated.


Solution

  • use SilverStripe\Control\Controller;
    
    class MyController extends Controller
    {
        private static $dependencies = [
            'logger' => '%$Psr\Log\LoggerInterface',
        ];
    
        // This will be set automatically, as long as MyController is instantiated via Injector
        public $logger;
    
        protected function init()
        {
            $this->logger->debug("MyController::init() called");
            parent::init();
        }
    }
    

    As described here:

    https://docs.silverstripe.org/en/4/developer_guides/debugging/error_handling/#accessing-the-logger-via-dependency-injection

    And even more info here: https://www.silverstripe.org/learn/lessons/v4/advanced-environment-configuration-1