ErrorHandler.php 8.51 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;
11
use yii\helpers\VarDumper;
Qiang Xue committed
12
use yii\web\HttpException;
13

Qiang Xue committed
14
/**
Qiang Xue committed
15
 * ErrorHandler handles uncaught PHP errors and exceptions.
Qiang Xue committed
16
 *
17
 * ErrorHandler is configured as an application component in [[\yii\base\Application]] by default.
18 19
 * You can access that instance via `Yii::$app->errorHandler`.
 *
Qiang Xue committed
20
 * @author Qiang Xue <qiang.xue@gmail.com>
21 22
 * @author Alexander Makarov <sam@rmcreative.ru>
 * @author Carsten Brandt <mail@cebe.cc>
Qiang Xue committed
23
 * @since 2.0
Qiang Xue committed
24
 */
25
abstract class ErrorHandler extends Component
Qiang Xue committed
26
{
27 28 29 30 31
    /**
     * @var boolean whether to discard any existing page output before error display. Defaults to true.
     */
    public $discardExistingOutput = true;
    /**
32 33 34 35
     * @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.
36
     */
37
    public $memoryReserveSize = 262144;
38 39 40 41
    /**
     * @var \Exception the exception that is being handled currently.
     */
    public $exception;
Qiang Xue committed
42

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

Qiang Xue committed
48

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

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

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

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

87
        // disable error capturing to avoid recursive errors while handling exceptions
88
        restore_error_handler();
89 90 91 92 93 94
        restore_exception_handler();
        try {
            $this->logException($exception);
            if ($this->discardExistingOutput) {
                $this->clearOutput();
            }
95
            $this->renderException($exception);
96
            if (!YII_ENV_TEST) {
97 98 99 100 101 102 103 104 105 106 107
                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 {
108
                    echo '<pre>' . htmlspecialchars($msg, ENT_QUOTES, Yii::$app->charset) . '</pre>';
109
                }
110
            }
111
            $msg .= "\n\$_SERVER = " . VarDumper::export($_SERVER);
112 113
            error_log($msg);
            exit(1);
114
        }
115

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

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

151 152
            throw $exception;
        }
153
    }
154

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

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

168
        $error = error_get_last();
resurtm committed
169

170 171 172
        if (ErrorException::isFatalError($error)) {
            $exception = new ErrorException($error['message'], $error['type'], $error['type'], $error['file'], $error['line']);
            $this->exception = $exception;
173 174

            $this->logException($exception);
175

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

            // need to explicitly flush logs because exit() next will terminate the app immediately
            Yii::getLogger()->flush(true);

184
            exit(1);
185 186
        }
    }
187

188
    /**
189
     * Renders the exception.
190
     * @param \Exception $exception the exception to be rendered.
191
     */
192
    abstract protected function renderException($exception);
193

194
    /**
195 196
     * Logs the given exception
     * @param \Exception $exception the exception to be logged
197
     */
198
    protected function logException($exception)
199
    {
200 201 202 203 204 205 206
        $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);
207 208 209
    }

    /**
210
     * Removes all output echoed before calling this method.
211
     */
212
    public function clearOutput()
213
    {
214 215 216 217
        // 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();
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 255 256 257 258

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