ErrorHandler.php 8.32 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
     * Handles uncaught PHP exceptions.
     *
     * This method is implemented as a PHP exception handler.
     *
     * @param \Exception $exception the exception that is not caught
68
     */
69
    public function handleException($exception)
70
    {
71
        if ($exception instanceof ExitException) {
72 73
            return;
        }
74

75
        $this->exception = $exception;
resurtm committed
76

77
        // disable error capturing to avoid recursive errors while handling exceptions
78
        restore_error_handler();
79 80 81 82 83 84
        restore_exception_handler();
        try {
            $this->logException($exception);
            if ($this->discardExistingOutput) {
                $this->clearOutput();
            }
85
            $this->renderException($exception);
86
            if (!YII_ENV_TEST) {
87 88 89 90 91 92 93 94 95 96 97
                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 {
98
                    echo '<pre>' . htmlspecialchars($msg, ENT_QUOTES, Yii::$app->charset) . '</pre>';
99
                }
100
            }
101 102 103
            $msg .= "\n\$_SERVER = " . var_export($_SERVER, true);
            error_log($msg);
            exit(1);
104
        }
105

106
        $this->exception = null;
107
    }
resurtm committed
108

109
    /**
110 111 112 113 114 115 116 117 118 119
     * 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
120
     */
121
    public function handleError($code, $message, $file, $line)
122
    {
Carsten Brandt committed
123
        if (error_reporting() & $code) {
124 125
            // load ErrorException manually here because autoloading them will not work
            // when error occurs while autoloading a class
Carsten Brandt committed
126
            if (!class_exists('yii\\base\\ErrorException', false)) {
127 128 129 130 131 132 133 134 135 136 137 138
                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);
                }
139
            }
resurtm committed
140

141 142
            throw $exception;
        }
143
    }
144

145
    /**
146
     * Handles fatal PHP errors
147
     */
148
    public function handleFatalError()
149
    {
150
        unset($this->_memoryReserve);
resurtm committed
151

152 153
        // load ErrorException manually here because autoloading them will not work
        // when error occurs while autoloading a class
Carsten Brandt committed
154
        if (!class_exists('yii\\base\\ErrorException', false)) {
155
            require_once(__DIR__ . '/ErrorException.php');
156
        }
resurtm committed
157

158
        $error = error_get_last();
resurtm committed
159

160 161 162 163
        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
164 165
            // 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);
166

167 168 169
            if ($this->discardExistingOutput) {
                $this->clearOutput();
            }
170
            $this->renderException($exception);
171
            exit(1);
172 173
        }
    }
174

175
    /**
176
     * Renders the exception.
177
     * @param \Exception $exception the exception to be rendered.
178
     */
179
    abstract protected function renderException($exception);
180

181
    /**
182 183
     * Logs the given exception
     * @param \Exception $exception the exception to be logged
184
     */
185
    protected function logException($exception)
186
    {
187 188 189 190 191 192 193
        $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);
194 195 196
    }

    /**
197
     * Removes all output echoed before calling this method.
198
     */
199
    public function clearOutput()
200
    {
201 202 203 204
        // 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();
205 206 207
            }
        }
    }
208 209 210 211 212 213 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

    /**
     * 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
246
}