Completed
Push — 2.1 ( 224aac...d335fd )
by Dmitry
54:21 queued 13:00
created

ErrorHandler::handleFallbackExceptionMessage()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 21
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 21
ccs 0
cts 4
cp 0
rs 9.0534
c 0
b 0
f 0
cc 4
eloc 17
nc 6
nop 2
crap 20
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\base;
9
10
use Yii;
11
use yii\helpers\VarDumper;
12
use yii\web\HttpException;
13
14
/**
15
 * ErrorHandler handles uncaught PHP errors and exceptions.
16
 *
17
 * ErrorHandler is configured as an application component in [[\yii\base\Application]] by default.
18
 * You can access that instance via `Yii::$app->errorHandler`.
19
 *
20
 * For more details and usage information on ErrorHandler, see the [guide article on handling errors](guide:runtime-handling-errors).
21
 *
22
 * @author Qiang Xue <[email protected]>
23
 * @author Alexander Makarov <[email protected]>
24
 * @author Carsten Brandt <[email protected]>
25
 * @since 2.0
26
 */
27
abstract class ErrorHandler extends Component
28
{
29
    /**
30
     * @var bool whether to discard any existing page output before error display. Defaults to true.
31
     */
32
    public $discardExistingOutput = true;
33
    /**
34
     * @var int the size of the reserved memory. A portion of memory is pre-allocated so that
35
     * when an out-of-memory issue occurs, the error handler is able to handle the error with
36
     * the help of this reserved memory. If you set this value to be 0, no memory will be reserved.
37
     * Defaults to 256KB.
38
     */
39
    public $memoryReserveSize = 262144;
40
    /**
41
     * @var \Exception the exception that is being handled currently.
42
     */
43
    public $exception;
44
45
    /**
46
     * @var string Used to reserve memory for fatal error handler.
47
     */
48
    private $_memoryReserve;
49
    /**
50
     * @var \Exception from HHVM error that stores backtrace
51
     */
52
    private $_hhvmException;
53
54
55
    /**
56
     * Register this error handler
57
     */
58
    public function register()
59
    {
60
        ini_set('display_errors', false);
61
        set_exception_handler([$this, 'handleException']);
62
        if (defined('HHVM_VERSION')) {
63
            set_error_handler([$this, 'handleHhvmError']);
64
        } else {
65
            set_error_handler([$this, 'handleError']);
66
        }
67
        if ($this->memoryReserveSize > 0) {
68
            $this->_memoryReserve = str_repeat('x', $this->memoryReserveSize);
69
        }
70
        register_shutdown_function([$this, 'handleFatalError']);
71
    }
72
73
    /**
74
     * Unregisters this error handler by restoring the PHP error and exception handlers.
75
     */
76
    public function unregister()
77
    {
78
        restore_error_handler();
79
        restore_exception_handler();
80
    }
81
82
    /**
83
     * Handles uncaught PHP exceptions.
84
     *
85
     * This method is implemented as a PHP exception handler.
86
     *
87
     * @param \Exception $exception the exception that is not caught
88
     */
89
    public function handleException($exception)
90
    {
91
        if ($exception instanceof ExitException) {
92
            return;
93
        }
94
95
        $this->exception = $exception;
96
97
        // disable error capturing to avoid recursive errors while handling exceptions
98
        $this->unregister();
99
100
        // set preventive HTTP status code to 500 in case error handling somehow fails and headers are sent
101
        // HTTP exceptions will override this value in renderException()
102
        if (PHP_SAPI !== 'cli') {
103
            http_response_code(500);
104
        }
105
106
        try {
107
            $this->logException($exception);
108
            if ($this->discardExistingOutput) {
109
                $this->clearOutput();
110
            }
111
            $this->renderException($exception);
112
            if (!YII_ENV_TEST) {
113
                \Yii::getLogger()->flush(true);
114
                if (defined('HHVM_VERSION')) {
115
                    flush();
116
                }
117
                exit(1);
118
            }
119
        } catch (\Exception $e) {
120
            // an other exception could be thrown while displaying the exception
121
            $this->handleFallbackExceptionMessage($e, $exception);
122
        } catch (\Throwable $e) {
0 ignored issues
show
Bug introduced by
The class Throwable does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
123
            // additional check for \Throwable introduced in PHP 7
124
            $this->handleFallbackExceptionMessage($e, $exception);
125
        }
126
127
        $this->exception = null;
128
    }
129
130
    /**
131
     * Handles exception thrown during exception processing in [[handleException()]].
132
     * @param \Exception|\Throwable $exception Exception that was thrown during main exception processing.
133
     * @param \Exception $previousException Main exception processed in [[handleException()]].
134
     * @since 2.0.11
135
     */
136
    protected function handleFallbackExceptionMessage($exception, $previousException) {
137
        $msg = "An Error occurred while handling another error:\n";
138
        $msg .= (string) $exception;
139
        $msg .= "\nPrevious exception:\n";
140
        $msg .= (string) $previousException;
141
        if (YII_DEBUG) {
142
            if (PHP_SAPI === 'cli') {
143
                echo $msg . "\n";
144
            } else {
145
                echo '<pre>' . htmlspecialchars($msg, ENT_QUOTES, Yii::$app->charset) . '</pre>';
146
            }
147
        } else {
148
            echo 'An internal server error occurred.';
149
        }
150
        $msg .= "\n\$_SERVER = " . VarDumper::export($_SERVER);
151
        error_log($msg);
152
        if (defined('HHVM_VERSION')) {
153
            flush();
154
        }
155
        exit(1);
156
    }
157
158
    /**
159
     * Handles HHVM execution errors such as warnings and notices.
160
     *
161
     * This method is used as a HHVM error handler. It will store exception that will
162
     * be used in fatal error handler
163
     *
164
     * @param int $code the level of the error raised.
165
     * @param string $message the error message.
166
     * @param string $file the filename that the error was raised in.
167
     * @param int $line the line number the error was raised at.
168
     * @param mixed $context
169
     * @param mixed $backtrace trace of error
170
     * @return bool whether the normal error handler continues.
171
     *
172
     * @throws ErrorException
173
     * @since 2.0.6
174
     */
175
    public function handleHhvmError($code, $message, $file, $line, $context, $backtrace)
176
    {
177
        if ($this->handleError($code, $message, $file, $line)) {
178
            return true;
179
        }
180
        if (E_ERROR & $code) {
181
            $exception = new ErrorException($message, $code, $code, $file, $line);
182
            $ref = new \ReflectionProperty('\Exception', 'trace');
183
            $ref->setAccessible(true);
184
            $ref->setValue($exception, $backtrace);
185
            $this->_hhvmException = $exception;
186
        }
187
        return false;
188
    }
189
190
    /**
191
     * Handles PHP execution errors such as warnings and notices.
192
     *
193
     * This method is used as a PHP error handler. It will simply raise an [[ErrorException]].
194
     *
195
     * @param int $code the level of the error raised.
196
     * @param string $message the error message.
197
     * @param string $file the filename that the error was raised in.
198
     * @param int $line the line number the error was raised at.
199
     * @return bool whether the normal error handler continues.
200
     *
201
     * @throws ErrorException
202
     */
203
    public function handleError($code, $message, $file, $line)
204
    {
205
        if (error_reporting() & $code) {
206
            // load ErrorException manually here because autoloading them will not work
207
            // when error occurs while autoloading a class
208
            if (!class_exists(ErrorException::class, false)) {
209
                require_once(__DIR__ . '/ErrorException.php');
210
            }
211
            $exception = new ErrorException($message, $code, $code, $file, $line);
212
213
            // in case error appeared in __toString method we can't throw any exception
214
            $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
215
            array_shift($trace);
216
            foreach ($trace as $frame) {
217
                if ($frame['function'] === '__toString') {
218
                    $this->handleException($exception);
219
                    if (defined('HHVM_VERSION')) {
220
                        flush();
221
                    }
222
                    exit(1);
223
                }
224
            }
225
226
            throw $exception;
227
        }
228
        return false;
229
    }
230
231
    /**
232
     * Handles fatal PHP errors
233
     */
234
    public function handleFatalError()
235
    {
236
        unset($this->_memoryReserve);
237
238
        // load ErrorException manually here because autoloading them will not
239
        // work when error occurs while autoloading a class
240
        if (!class_exists(ErrorException::class, false)) {
241
            require_once(__DIR__ . '/ErrorException.php');
242
        }
243
244
        $error = error_get_last();
245
246
        if (ErrorException::isFatalError($error)) {
247
            if (!empty($this->_hhvmException)) {
248
                $exception = $this->_hhvmException;
249
            } else {
250
                $exception = new ErrorException($error['message'], $error['type'], $error['type'], $error['file'], $error['line']);
251
            }
252
            $this->exception = $exception;
253
254
            $this->logException($exception);
255
256
            if ($this->discardExistingOutput) {
257
                $this->clearOutput();
258
            }
259
            $this->renderException($exception);
260
261
            // need to explicitly flush logs because exit() next will terminate the app immediately
262
            Yii::getLogger()->flush(true);
263
            if (defined('HHVM_VERSION')) {
264
                flush();
265
            }
266
            exit(1);
267
        }
268
    }
269
270
    /**
271
     * Renders the exception.
272
     * @param \Exception $exception the exception to be rendered.
273
     */
274
    abstract protected function renderException($exception);
275
276
    /**
277
     * Logs the given exception
278
     * @param \Exception $exception the exception to be logged
279
     * @since 2.0.3 this method is now public.
280
     */
281
    public function logException($exception)
282
    {
283
        $category = get_class($exception);
284
        if ($exception instanceof HttpException) {
285
            $category = HttpException::class . ': ' . $exception->statusCode;
286
        } elseif ($exception instanceof \ErrorException) {
287
            $category .= ':' . $exception->getSeverity();
288
        }
289
        Yii::error($exception, $category);
290
    }
291
292
    /**
293
     * Removes all output echoed before calling this method.
294
     */
295
    public function clearOutput()
296
    {
297
        // the following manual level counting is to deal with zlib.output_compression set to On
298
        for ($level = ob_get_level(); $level > 0; --$level) {
299
            if (!@ob_end_clean()) {
300
                ob_clean();
301
            }
302
        }
303
    }
304
305
    /**
306
     * Converts an exception into a PHP error.
307
     *
308
     * This method can be used to convert exceptions inside of methods like `__toString()`
309
     * to PHP errors because exceptions cannot be thrown inside of them.
310
     * @param \Exception $exception the exception to convert to a PHP error.
311
     */
312
    public static function convertExceptionToError($exception)
313
    {
314
        trigger_error(static::convertExceptionToString($exception), E_USER_ERROR);
315
    }
316
317
    /**
318
     * Converts an exception into a simple string.
319
     * @param \Exception $exception the exception being converted
320
     * @return string the string representation of the exception.
321
     */
322
    public static function convertExceptionToString($exception)
323
    {
324
        if ($exception instanceof Exception && ($exception instanceof UserException || !YII_DEBUG)) {
325
            $message = "{$exception->getName()}: {$exception->getMessage()}";
326
        } elseif (YII_DEBUG) {
327
            if ($exception instanceof Exception) {
328
                $message = "Exception ({$exception->getName()})";
329
            } elseif ($exception instanceof ErrorException) {
330
                $message = "{$exception->getName()}";
331
            } else {
332
                $message = 'Exception';
333
            }
334
            $message .= " '" . get_class($exception) . "' with message '{$exception->getMessage()}' \n\nin "
335
                . $exception->getFile() . ':' . $exception->getLine() . "\n\n"
336
                . "Stack trace:\n" . $exception->getTraceAsString();
337
        } else {
338
            $message = 'Error: ' . $exception->getMessage();
339
        }
340
        return $message;
341
    }
342
}
343