phpyii2rollbar

Yii2 Custom Error Handler for Rollbar - Errors should not be displayed in browser


I need to create a custom error handler by extending rollbar error handler that should always handle fatal errors, but handle notice errors only if we are in debug mode. In production mode, all notice errors should not be displayed in the browser instead it should be logged in rollbar and get notified. Can anyone suggest an idea on how to go with this error handling?

I just started by extending Yii2 base error handler,

<?php
namespace common\components;
class ErrorHandler extends \yii\web\ErrorHandler
{
    public function register()
    {
        ini_set('display_errors', false);
        set_exception_handler([$this, 'handleException']);
        register_shutdown_function([$this, 'handleFatalError']);
    }
}

With this above code, I'm able to hide notice error from browser and get logged in php error log. Now the thing is I need to get log in rollbar and get notified as usual.


Solution

  • I solved it with the following code.

    /**
     * Handles PHP execution errors such as warnings and notices.
     *
     * This method is used as a PHP error handler. It will simply raise an [[ErrorException]].
     *
     * @param int $code the level of the error raised.
     * @param string $message the error message.
     * @param string $file the filename that the error was raised in.
     * @param int $line the line number the error was raised at.
     * @return bool whether the normal error handler continues.
     *
     * @throws ErrorException
     */
    
    public function handleError($code, $message, $file, $line)
    {
        if (error_reporting() & $code) {
            $exception = new \yii\base\ErrorException($message, $code, $code, $file, $line);
            if (YII_ENV_PROD) {
                $this->logException($exception);
            } else {
                throw $exception;
            }
        }
        return false;
    }