Passed
Pull Request — master (#19402)
by Fedonyuk
08:33
created

ErrorHandler::logException()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
eloc 6
nc 3
nop 1
dl 0
loc 9
ccs 0
cts 7
cp 0
crap 12
rs 10
c 0
b 0
f 0
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
     * @event Event an event that is triggered when the handler is called by shutdown function via [[handleFatalError()]].
31
     * @since 2.0.46
32
     */
33
    const EVENT_SHUTDOWN = 'shutdown';
34
35
    /**
36
     * @var bool whether to discard any existing page output before error display. Defaults to true.
37
     */
38
    public $discardExistingOutput = true;
39
    /**
40
     * @var int the size of the reserved memory. A portion of memory is pre-allocated so that
41
     * when an out-of-memory issue occurs, the error handler is able to handle the error with
42
     * the help of this reserved memory. If you set this value to be 0, no memory will be reserved.
43
     * Defaults to 256KB.
44
     */
45
    public $memoryReserveSize = 262144;
46
    /**
47
     * @var \Throwable|null the exception that is being handled currently.
48
     */
49
    public $exception;
50
    /**
51
     * @var bool if true - `handleException()` will finish script with `ExitCode::OK`.
52
     * false - `ExitCode::UNSPECIFIED_ERROR`.
53
     * @since 2.0.36
54
     */
55
    public $silentExitOnException;
56
57
    /**
58
     * @var string Used to reserve memory for fatal error handler.
59
     */
60
    private $_memoryReserve;
61
    /**
62
     * @var \Throwable from HHVM error that stores backtrace
63
     */
64
    private $_hhvmException;
65
    /**
66
     * @var bool whether this instance has been registered using `register()`
67
     */
68
    private $_registered = false;
69
    /**
70
     * @var string the current working directory
71
     */
72
    private $_workingDirectory;
73
74
75 243
    public function init()
76
    {
77 243
        $this->silentExitOnException = $this->silentExitOnException !== null ? $this->silentExitOnException : YII_ENV_TEST;
78 243
        parent::init();
79 243
    }
80
81
    /**
82
     * Register this error handler.
83
     *
84
     * @since 2.0.32 this will not do anything if the error handler was already registered
85
     */
86
    public function register()
87
    {
88
        if (!$this->_registered) {
89
            ini_set('display_errors', false);
0 ignored issues
show
Bug introduced by
false of type false is incompatible with the type string expected by parameter $value of ini_set(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

89
            ini_set('display_errors', /** @scrutinizer ignore-type */ false);
Loading history...
90
            set_exception_handler([$this, 'handleException']);
91
            if (defined('HHVM_VERSION')) {
92
                set_error_handler([$this, 'handleHhvmError']);
93
            } else {
94
                set_error_handler([$this, 'handleError']);
95
            }
96
            if ($this->memoryReserveSize > 0) {
97
                $this->_memoryReserve = str_repeat('x', $this->memoryReserveSize);
98
            }
99
            register_shutdown_function([$this, 'handleFatalError']);
100
            $this->_registered = true;
101
            // to restore working directory in shutdown handler
102
            $this->_workingDirectory = getcwd();
103
        }
104
    }
105
106
    /**
107
     * Unregisters this error handler by restoring the PHP error and exception handlers.
108
     * @since 2.0.32 this will not do anything if the error handler was not registered
109
     */
110
    public function unregister()
111
    {
112
        if ($this->_registered) {
113
            restore_error_handler();
114
            restore_exception_handler();
115
            $this->_registered = false;
116
        }
117
    }
118
119
    /**
120
     * Handles uncaught PHP exceptions.
121
     *
122
     * This method is implemented as a PHP exception handler.
123
     *
124
     * @param \Throwable $exception the exception that is not caught
125
     */
126
    public function handleException($exception)
127
    {
128
        if ($exception instanceof ExitException) {
129
            return;
130
        }
131
132
        $this->exception = $exception;
133
134
        // disable error capturing to avoid recursive errors while handling exceptions
135
        $this->unregister();
136
137
        // set preventive HTTP status code to 500 in case error handling somehow fails and headers are sent
138
        // HTTP exceptions will override this value in renderException()
139
        if (PHP_SAPI !== 'cli') {
140
            http_response_code(500);
141
        }
142
143
        try {
144
            $this->logException($exception);
145
            if ($this->discardExistingOutput) {
146
                $this->clearOutput();
147
            }
148
            $this->renderException($exception);
149
            if (!$this->silentExitOnException) {
150
                \Yii::getLogger()->flush(true);
151
                if (defined('HHVM_VERSION')) {
152
                    flush();
153
                }
154
                exit(1);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
155
            }
156
        } catch (\Exception $e) {
157
            // an other exception could be thrown while displaying the exception
158
            $this->handleFallbackExceptionMessage($e, $exception);
159
        } catch (\Throwable $e) {
160
            // additional check for \Throwable introduced in PHP 7
161
            $this->handleFallbackExceptionMessage($e, $exception);
162
        }
163
164
        $this->exception = null;
165
    }
166
167
    /**
168
     * Handles exception thrown during exception processing in [[handleException()]].
169
     * @param \Throwable $exception Exception that was thrown during main exception processing.
170
     * @param \Throwable $previousException Main exception processed in [[handleException()]].
171
     * @since 2.0.11
172
     */
173
    protected function handleFallbackExceptionMessage($exception, $previousException)
174
    {
175
        $msg = "An Error occurred while handling another error:\n";
176
        $msg .= (string) $exception;
177
        $msg .= "\nPrevious exception:\n";
178
        $msg .= (string) $previousException;
179
        if (YII_DEBUG) {
180
            if (PHP_SAPI === 'cli') {
181
                echo $msg . "\n";
182
            } else {
183
                echo '<pre>' . htmlspecialchars($msg, ENT_QUOTES, Yii::$app->charset) . '</pre>';
184
            }
185
            $msg .= "\n\$_SERVER = " . VarDumper::export($_SERVER);
186
        } else {
187
            echo 'An internal server error occurred.';
188
        }
189
        error_log($msg);
190
        if (defined('HHVM_VERSION')) {
191
            flush();
192
        }
193
        exit(1);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
194
    }
195
196
    /**
197
     * Handles HHVM execution errors such as warnings and notices.
198
     *
199
     * This method is used as a HHVM error handler. It will store exception that will
200
     * be used in fatal error handler
201
     *
202
     * @param int $code the level of the error raised.
203
     * @param string $message the error message.
204
     * @param string $file the filename that the error was raised in.
205
     * @param int $line the line number the error was raised at.
206
     * @param mixed $context
207
     * @param mixed $backtrace trace of error
208
     * @return bool whether the normal error handler continues.
209
     *
210
     * @throws ErrorException
211
     * @since 2.0.6
212
     */
213
    public function handleHhvmError($code, $message, $file, $line, $context, $backtrace)
214
    {
215
        if ($this->handleError($code, $message, $file, $line)) {
216
            return true;
217
        }
218
        if (E_ERROR & $code) {
219
            $exception = new ErrorException($message, $code, $code, $file, $line);
220
            $ref = new \ReflectionProperty('\Exception', 'trace');
221
            $ref->setAccessible(true);
222
            $ref->setValue($exception, $backtrace);
223
            $this->_hhvmException = $exception;
224
        }
225
226
        return false;
227
    }
228
229
    /**
230
     * Handles PHP execution errors such as warnings and notices.
231
     *
232
     * This method is used as a PHP error handler. It will simply raise an [[ErrorException]].
233
     *
234
     * @param int $code the level of the error raised.
235
     * @param string $message the error message.
236
     * @param string $file the filename that the error was raised in.
237
     * @param int $line the line number the error was raised at.
238
     * @return bool whether the normal error handler continues.
239
     *
240
     * @throws ErrorException
241
     */
242
    public function handleError($code, $message, $file, $line)
243
    {
244
        if (error_reporting() & $code) {
245
            // load ErrorException manually here because autoloading them will not work
246
            // when error occurs while autoloading a class
247
            if (!class_exists('yii\\base\\ErrorException', false)) {
248
                require_once __DIR__ . '/ErrorException.php';
249
            }
250
            $exception = new ErrorException($message, $code, $code, $file, $line);
251
252
            if (PHP_VERSION_ID < 70400) {
253
                // prior to PHP 7.4 we can't throw exceptions inside of __toString() - it will result a fatal error
254
                $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
255
                array_shift($trace);
256
                foreach ($trace as $frame) {
257
                    if ($frame['function'] === '__toString') {
258
                        $this->handleException($exception);
259
                        if (defined('HHVM_VERSION')) {
260
                            flush();
261
                        }
262
                        exit(1);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
263
                    }
264
                }
265
            }
266
267
            throw $exception;
268
        }
269
270
        return false;
271
    }
272
273
    /**
274
     * Handles fatal PHP errors.
275
     */
276
    public function handleFatalError()
277
    {
278
        $this->_memoryReserve = null;
279
280
        // fix working directory for some Web servers e.g. Apache
281
        chdir($this->_workingDirector);
0 ignored issues
show
Bug Best Practice introduced by
The property _workingDirector does not exist on yii\base\ErrorHandler. Since you implemented __get, consider adding a @property annotation.
Loading history...
282
283
        // load ErrorException manually here because autoloading them will not work
284
        // when error occurs while autoloading a class
285
        if (!class_exists('yii\\base\\ErrorException', false)) {
286
            require_once __DIR__ . '/ErrorException.php';
287
        }
288
289
        $error = error_get_last();
290
291
        if (ErrorException::isFatalError($error)) {
292
            if (!empty($this->_hhvmException)) {
293
                $exception = $this->_hhvmException;
294
            } else {
295
                $exception = new ErrorException($error['message'], $error['type'], $error['type'], $error['file'], $error['line']);
296
            }
297
            $this->exception = $exception;
298
299
            $this->logException($exception);
300
301
            if ($this->discardExistingOutput) {
302
                $this->clearOutput();
303
            }
304
            $this->renderException($exception);
305
306
            // need to explicitly flush logs because exit() next will terminate the app immediately
307
            Yii::getLogger()->flush(true);
308
            if (defined('HHVM_VERSION')) {
309
                flush();
310
            }
311
312
            $this->trigger(static::EVENT_SHUTDOWN);
313
314
            exit(1);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
315
        }
316
    }
317
318
    /**
319
     * Renders the exception.
320
     * @param \Throwable $exception the exception to be rendered.
321
     */
322
    abstract protected function renderException($exception);
323
324
    /**
325
     * Logs the given exception.
326
     * @param \Throwable $exception the exception to be logged
327
     * @since 2.0.3 this method is now public.
328
     */
329
    public function logException($exception)
330
    {
331
        $category = get_class($exception);
332
        if ($exception instanceof HttpException) {
333
            $category = 'yii\\web\\HttpException:' . $exception->statusCode;
334
        } elseif ($exception instanceof \ErrorException) {
335
            $category .= ':' . $exception->getSeverity();
336
        }
337
        Yii::error($exception, $category);
338
    }
339
340
    /**
341
     * Removes all output echoed before calling this method.
342
     */
343
    public function clearOutput()
344
    {
345
        // the following manual level counting is to deal with zlib.output_compression set to On
346
        for ($level = ob_get_level(); $level > 0; --$level) {
347
            if (!@ob_end_clean()) {
348
                ob_clean();
349
            }
350
        }
351
    }
352
353
    /**
354
     * Converts an exception into a PHP error.
355
     *
356
     * This method can be used to convert exceptions inside of methods like `__toString()`
357
     * to PHP errors because exceptions cannot be thrown inside of them.
358
     * @param \Throwable $exception the exception to convert to a PHP error.
359
     */
360
    public static function convertExceptionToError($exception)
361
    {
362
        trigger_error(static::convertExceptionToString($exception), E_USER_ERROR);
363
    }
364
365
    /**
366
     * Converts an exception into a simple string.
367
     * @param \Throwable $exception the exception being converted
368
     * @return string the string representation of the exception.
369
     */
370
    public static function convertExceptionToString($exception)
371
    {
372
        if ($exception instanceof UserException) {
373
            return "{$exception->getName()}: {$exception->getMessage()}";
374
        }
375
376
        if (YII_DEBUG) {
377
            return static::convertExceptionToVerboseString($exception);
378
        }
379
380
        return 'An internal server error occurred.';
381
    }
382
383
    /**
384
     * Converts an exception into a string that has verbose information about the exception and its trace.
385
     * @param \Throwable $exception the exception being converted
386
     * @return string the string representation of the exception.
387
     *
388
     * @since 2.0.14
389
     */
390 1
    public static function convertExceptionToVerboseString($exception)
391
    {
392 1
        if ($exception instanceof Exception) {
393
            $message = "Exception ({$exception->getName()})";
394 1
        } elseif ($exception instanceof ErrorException) {
395
            $message = (string)$exception->getName();
396
        } else {
397 1
            $message = 'Exception';
398
        }
399 1
        $message .= " '" . get_class($exception) . "' with message '{$exception->getMessage()}' \n\nin "
400 1
            . $exception->getFile() . ':' . $exception->getLine() . "\n\n"
401 1
            . "Stack trace:\n" . $exception->getTraceAsString();
402
403 1
        return $message;
404
    }
405
}
406