ErrorHandler.php 8.53 KB
Newer Older
Qiang Xue committed
1 2 3
<?php
/**
 * @link http://www.yiiframework.com/
Qiang Xue committed
4
 * @copyright Copyright (c) 2008 Yii Software LLC
Qiang Xue committed
5 6 7
 * @license http://www.yiiframework.com/license/
 */

Qiang Xue committed
8
namespace yii\base;
Qiang Xue committed
9

10
use Yii;
Qiang Xue committed
11
use yii\web\HttpException;
12

Qiang Xue committed
13
/**
Qiang Xue committed
14
 * ErrorHandler handles uncaught PHP errors and exceptions.
Qiang Xue committed
15
 *
16
 * ErrorHandler is configured as an application component in [[\yii\base\Application]] by default.
17 18
 * You can access that instance via `Yii::$app->errorHandler`.
 *
Qiang Xue committed
19
 * @author Qiang Xue <qiang.xue@gmail.com>
20 21
 * @author Alexander Makarov <sam@rmcreative.ru>
 * @author Carsten Brandt <mail@cebe.cc>
Qiang Xue committed
22
 * @since 2.0
Qiang Xue committed
23
 */
24
abstract class ErrorHandler extends Component
Qiang Xue committed
25
{
26 27 28 29 30
    /**
     * @var boolean whether to discard any existing page output before error display. Defaults to true.
     */
    public $discardExistingOutput = true;
    /**
31 32 33 34
     * @var integer the size of the reserved memory. A portion of memory is pre-allocated so that
     * when an out-of-memory issue occurs, the error handler is able to handle the error with
     * the help of this reserved memory. If you set this value to be 0, no memory will be reserved.
     * Defaults to 256KB.
35
     */
36
    public $memoryReserveSize = 262144;
37 38 39 40
    /**
     * @var \Exception the exception that is being handled currently.
     */
    public $exception;
Qiang Xue committed
41

42
    /**
43
     * @var string Used to reserve memory for fatal error handler.
44
     */
45
    private $_memoryReserve;
46

Qiang Xue committed
47

48
    /**
49
     * Register this error handler
50
     */
51
    public function register()
52
    {
53
        ini_set('display_errors', false);
54
        set_exception_handler([$this, 'handleException']);
Carsten Brandt committed
55
        set_error_handler([$this, 'handleError']);
56 57
        if ($this->memoryReserveSize > 0) {
            $this->_memoryReserve = str_repeat('x', $this->memoryReserveSize);
58
        }
59
        register_shutdown_function([$this, 'handleFatalError']);
60
    }
Qiang Xue committed
61

62 63 64 65 66 67 68 69 70
    /**
     * Deregister this error handler by restoring the PHP error and exception handlers.
     */
    public function deRegister()
    {
        restore_error_handler();
        restore_exception_handler();
    }

71
    /**
72 73 74 75 76
     * Handles uncaught PHP exceptions.
     *
     * This method is implemented as a PHP exception handler.
     *
     * @param \Exception $exception the exception that is not caught
77
     */
78
    public function handleException($exception)
79
    {
80
        if ($exception instanceof ExitException) {
81 82
            return;
        }
83

84
        $this->exception = $exception;
resurtm committed
85

86
        // disable error capturing to avoid recursive errors while handling exceptions
87
        restore_error_handler();
88 89 90 91 92 93
        restore_exception_handler();
        try {
            $this->logException($exception);
            if ($this->discardExistingOutput) {
                $this->clearOutput();
            }
94
            $this->renderException($exception);
95
            if (!YII_ENV_TEST) {
96 97 98 99 100 101 102 103 104 105 106
                exit(1);
            }
        } catch (\Exception $e) {
            // an other exception could be thrown while displaying the exception
            $msg = (string) $e;
            $msg .= "\nPrevious exception:\n";
            $msg .= (string) $exception;
            if (YII_DEBUG) {
                if (PHP_SAPI === 'cli') {
                    echo $msg . "\n";
                } else {
107
                    echo '<pre>' . htmlspecialchars($msg, ENT_QUOTES, Yii::$app->charset) . '</pre>';
108
                }
109
            }
110 111 112
            $msg .= "\n\$_SERVER = " . var_export($_SERVER, true);
            error_log($msg);
            exit(1);
113
        }
114

115
        $this->exception = null;
116
    }
resurtm committed
117

118
    /**
119 120 121 122 123 124 125 126 127 128
     * 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 integer $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 integer $line the line number the error was raised at.
     *
     * @throws ErrorException
129
     */
130
    public function handleError($code, $message, $file, $line)
131
    {
Carsten Brandt committed
132
        if (error_reporting() & $code) {
133 134
            // load ErrorException manually here because autoloading them will not work
            // when error occurs while autoloading a class
Carsten Brandt committed
135
            if (!class_exists('yii\\base\\ErrorException', false)) {
136 137 138 139 140 141 142 143 144 145 146 147
                require_once(__DIR__ . '/ErrorException.php');
            }
            $exception = new ErrorException($message, $code, $code, $file, $line);

            // in case error appeared in __toString method we can't throw any exception
            $trace = debug_backtrace(0);
            array_shift($trace);
            foreach ($trace as $frame) {
                if ($frame['function'] == '__toString') {
                    $this->handleException($exception);
                    exit(1);
                }
148
            }
resurtm committed
149

150 151
            throw $exception;
        }
152
    }
153

154
    /**
155
     * Handles fatal PHP errors
156
     */
157
    public function handleFatalError()
158
    {
159
        unset($this->_memoryReserve);
resurtm committed
160

161 162
        // load ErrorException manually here because autoloading them will not work
        // when error occurs while autoloading a class
Carsten Brandt committed
163
        if (!class_exists('yii\\base\\ErrorException', false)) {
164
            require_once(__DIR__ . '/ErrorException.php');
165
        }
resurtm committed
166

167
        $error = error_get_last();
resurtm committed
168

169 170 171 172
        if (ErrorException::isFatalError($error)) {
            $exception = new ErrorException($error['message'], $error['type'], $error['type'], $error['file'], $error['line']);
            $this->exception = $exception;
            // use error_log because it's too late to use Yii log
173 174
            // also do not log when on CLI SAPI because message will be sent to STDERR which has already been done by PHP
            PHP_SAPI === 'cli' or error_log($exception);
175

176 177 178
            if ($this->discardExistingOutput) {
                $this->clearOutput();
            }
179
            $this->renderException($exception);
180
            exit(1);
181 182
        }
    }
183

184
    /**
185
     * Renders the exception.
186
     * @param \Exception $exception the exception to be rendered.
187
     */
188
    abstract protected function renderException($exception);
189

190
    /**
191 192
     * Logs the given exception
     * @param \Exception $exception the exception to be logged
193
     */
194
    protected function logException($exception)
195
    {
196 197 198 199 200 201 202
        $category = get_class($exception);
        if ($exception instanceof HttpException) {
            $category = 'yii\\web\\HttpException:' . $exception->statusCode;
        } elseif ($exception instanceof \ErrorException) {
            $category .= ':' . $exception->getSeverity();
        }
        Yii::error((string) $exception, $category);
203 204 205
    }

    /**
206
     * Removes all output echoed before calling this method.
207
     */
208
    public function clearOutput()
209
    {
210 211 212 213
        // the following manual level counting is to deal with zlib.output_compression set to On
        for ($level = ob_get_level(); $level > 0; --$level) {
            if (!@ob_end_clean()) {
                ob_clean();
214 215 216
            }
        }
    }
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254

    /**
     * Converts an exception into a PHP error.
     *
     * This method can be used to convert exceptions inside of methods like `__toString()`
     * to PHP errors because exceptions cannot be thrown inside of them.
     * @param \Exception $exception the exception to convert to a PHP error.
     */
    public static function convertExceptionToError($exception)
    {
        trigger_error(static::convertExceptionToString($exception), E_USER_ERROR);
    }

    /**
     * Converts an exception into a simple string.
     * @param \Exception $exception the exception being converted
     * @return string the string representation of the exception.
     */
    public static function convertExceptionToString($exception)
    {
        if ($exception instanceof Exception && ($exception instanceof UserException || !YII_DEBUG)) {
            $message = "{$exception->getName()}: {$exception->getMessage()}";
        } elseif (YII_DEBUG) {
            if ($exception instanceof Exception) {
                $message = "Exception ({$exception->getName()})";
            } elseif ($exception instanceof ErrorException) {
                $message = "{$exception->getName()}";
            } else {
                $message = 'Exception';
            }
            $message .= " '" . get_class($exception) . "' with message '{$exception->getMessage()}' \n\nin "
                . $exception->getFile() . ':' . $exception->getLine() . "\n\n"
                . "Stack trace:\n" . $exception->getTraceAsString();
        } else {
            $message = 'Error: ' . $exception->getMessage();
        }
        return $message;
    }
Qiang Xue committed
255
}