ErrorHandler.php 8.58 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 89
        $this->unregister();

90 91 92 93 94
        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
     * 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.
128
     * @return boolean whether the normal error handler continues.
129 130
     *
     * @throws ErrorException
131
     */
132
    public function handleError($code, $message, $file, $line)
133
    {
Carsten Brandt committed
134
        if (error_reporting() & $code) {
135 136
            // load ErrorException manually here because autoloading them will not work
            // when error occurs while autoloading a class
Carsten Brandt committed
137
            if (!class_exists('yii\\base\\ErrorException', false)) {
138 139 140 141 142
                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
143
            $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
144 145 146 147 148 149
            array_shift($trace);
            foreach ($trace as $frame) {
                if ($frame['function'] == '__toString') {
                    $this->handleException($exception);
                    exit(1);
                }
150
            }
resurtm committed
151

152 153
            throw $exception;
        }
154
        return false;
155
    }
156

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

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

170
        $error = error_get_last();
resurtm committed
171

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

            $this->logException($exception);
177

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

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

186
            exit(1);
187 188
        }
    }
189

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

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

    /**
212
     * Removes all output echoed before calling this method.
213
     */
214
    public function clearOutput()
215
    {
216 217 218 219
        // 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();
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 259 260

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