-
-
Notifications
You must be signed in to change notification settings - Fork 6.9k
/
ErrorHandler.php
427 lines (386 loc) · 14.1 KB
/
ErrorHandler.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
namespace yii\base;
use Yii;
use yii\helpers\VarDumper;
use yii\web\HttpException;
/**
* ErrorHandler handles uncaught PHP errors and exceptions.
*
* ErrorHandler is configured as an application component in [[\yii\base\Application]] by default.
* You can access that instance via `Yii::$app->errorHandler`.
*
* For more details and usage information on ErrorHandler, see the [guide article on handling errors](guide:runtime-handling-errors).
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @author Alexander Makarov <sam@rmcreative.ru>
* @author Carsten Brandt <mail@cebe.cc>
* @since 2.0
*/
abstract class ErrorHandler extends Component
{
/**
* @event Event an event that is triggered when the handler is called by shutdown function via [[handleFatalError()]].
* @since 2.0.46
*/
const EVENT_SHUTDOWN = 'shutdown';
/**
* @var bool whether to discard any existing page output before error display. Defaults to true.
*/
public $discardExistingOutput = true;
/**
* @var int 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.
*/
public $memoryReserveSize = 262144;
/**
* @var \Throwable|null the exception that is being handled currently.
*/
public $exception;
/**
* @var bool if true - `handleException()` will finish script with `ExitCode::OK`.
* false - `ExitCode::UNSPECIFIED_ERROR`.
* @since 2.0.36
*/
public $silentExitOnException;
/**
* @var string Used to reserve memory for fatal error handler.
*/
private $_memoryReserve;
/**
* @var \Throwable from HHVM error that stores backtrace
*/
private $_hhvmException;
/**
* @var bool whether this instance has been registered using `register()`
*/
private $_registered = false;
/**
* @var string the current working directory
*/
private $_workingDirectory;
public function init()
{
$this->silentExitOnException = $this->silentExitOnException !== null ? $this->silentExitOnException : YII_ENV_TEST;
parent::init();
}
/**
* Register this error handler.
*
* @since 2.0.32 this will not do anything if the error handler was already registered
*/
public function register()
{
if (!$this->_registered) {
ini_set('display_errors', false);
set_exception_handler([$this, 'handleException']);
if (defined('HHVM_VERSION')) {
set_error_handler([$this, 'handleHhvmError']);
} else {
set_error_handler([$this, 'handleError']);
}
if ($this->memoryReserveSize > 0) {
$this->_memoryReserve = str_repeat('x', $this->memoryReserveSize);
}
// to restore working directory in shutdown handler
if (PHP_SAPI !== 'cli') {
$this->_workingDirectory = getcwd();
}
register_shutdown_function([$this, 'handleFatalError']);
$this->_registered = true;
}
}
/**
* Unregisters this error handler by restoring the PHP error and exception handlers.
* @since 2.0.32 this will not do anything if the error handler was not registered
*/
public function unregister()
{
if ($this->_registered) {
$this->_memoryReserve = null;
$this->_workingDirectory = null;
restore_error_handler();
restore_exception_handler();
$this->_registered = false;
}
}
/**
* Handles uncaught PHP exceptions.
*
* This method is implemented as a PHP exception handler.
*
* @param \Throwable $exception the exception that is not caught
*/
public function handleException($exception)
{
if ($exception instanceof ExitException) {
return;
}
$this->exception = $exception;
// disable error capturing to avoid recursive errors while handling exceptions
$this->unregister();
// set preventive HTTP status code to 500 in case error handling somehow fails and headers are sent
// HTTP exceptions will override this value in renderException()
if (PHP_SAPI !== 'cli') {
http_response_code(500);
}
try {
$this->logException($exception);
if ($this->discardExistingOutput) {
$this->clearOutput();
}
$this->renderException($exception);
if (!$this->silentExitOnException) {
\Yii::getLogger()->flush(true);
if (defined('HHVM_VERSION')) {
flush();
}
exit(1);
}
} catch (\Exception $e) {
// an other exception could be thrown while displaying the exception
$this->handleFallbackExceptionMessage($e, $exception);
} catch (\Throwable $e) {
// additional check for \Throwable introduced in PHP 7
$this->handleFallbackExceptionMessage($e, $exception);
}
$this->exception = null;
}
/**
* Handles exception thrown during exception processing in [[handleException()]].
* @param \Throwable $exception Exception that was thrown during main exception processing.
* @param \Throwable $previousException Main exception processed in [[handleException()]].
* @since 2.0.11
*/
protected function handleFallbackExceptionMessage($exception, $previousException)
{
$msg = "An Error occurred while handling another error:\n";
$msg .= (string) $exception;
$msg .= "\nPrevious exception:\n";
$msg .= (string) $previousException;
if (YII_DEBUG) {
if (PHP_SAPI === 'cli') {
echo $msg . "\n";
} else {
echo '<pre>' . htmlspecialchars($msg, ENT_QUOTES, Yii::$app->charset) . '</pre>';
}
$msg .= "\n\$_SERVER = " . VarDumper::export($_SERVER);
} else {
echo 'An internal server error occurred.';
}
error_log($msg);
if (defined('HHVM_VERSION')) {
flush();
}
exit(1);
}
/**
* Handles HHVM execution errors such as warnings and notices.
*
* This method is used as a HHVM error handler. It will store exception that will
* be used in fatal error handler
*
* @param int $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 int $line the line number the error was raised at.
* @param mixed $context
* @param mixed $backtrace trace of error
* @return bool whether the normal error handler continues.
*
* @throws ErrorException
* @since 2.0.6
*/
public function handleHhvmError($code, $message, $file, $line, $context, $backtrace)
{
if ($this->handleError($code, $message, $file, $line)) {
return true;
}
if (E_ERROR & $code) {
$exception = new ErrorException($message, $code, $code, $file, $line);
$ref = new \ReflectionProperty('\Exception', 'trace');
$ref->setAccessible(true);
$ref->setValue($exception, $backtrace);
$this->_hhvmException = $exception;
}
return false;
}
/**
* 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 int $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 int $line the line number the error was raised at.
* @return bool whether the normal error handler continues.
*
* @throws ErrorException
*/
public function handleError($code, $message, $file, $line)
{
if (error_reporting() & $code) {
// load ErrorException manually here because autoloading them will not work
// when error occurs while autoloading a class
if (!class_exists('yii\\base\\ErrorException', false)) {
require_once __DIR__ . '/ErrorException.php';
}
$exception = new ErrorException($message, $code, $code, $file, $line);
if (PHP_VERSION_ID < 70400) {
// prior to PHP 7.4 we can't throw exceptions inside of __toString() - it will result a fatal error
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
array_shift($trace);
foreach ($trace as $frame) {
if ($frame['function'] === '__toString') {
$this->handleException($exception);
if (defined('HHVM_VERSION')) {
flush();
}
exit(1);
}
}
}
throw $exception;
}
return false;
}
/**
* Handles fatal PHP errors.
*/
public function handleFatalError()
{
$this->_memoryReserve = null;
if (!empty($this->_workingDirectory)) {
// fix working directory for some Web servers e.g. Apache
chdir($this->_workingDirectory);
// flush memory
$this->_workingDirectory = null;
}
$error = error_get_last();
if ($error === null) {
return;
}
// load ErrorException manually here because autoloading them will not work
// when error occurs while autoloading a class
if (!class_exists('yii\\base\\ErrorException', false)) {
require_once __DIR__ . '/ErrorException.php';
}
if (!ErrorException::isFatalError($error)) {
return;
}
if (!empty($this->_hhvmException)) {
$this->exception = $this->_hhvmException;
} else {
$this->exception = new ErrorException(
$error['message'],
$error['type'],
$error['type'],
$error['file'],
$error['line']
);
}
unset($error);
$this->logException($this->exception);
if ($this->discardExistingOutput) {
$this->clearOutput();
}
$this->renderException($this->exception);
// need to explicitly flush logs because exit() next will terminate the app immediately
Yii::getLogger()->flush(true);
if (defined('HHVM_VERSION')) {
flush();
}
$this->trigger(static::EVENT_SHUTDOWN);
// ensure it is called after user-defined shutdown functions
register_shutdown_function(function () {
exit(1);
});
}
/**
* Renders the exception.
* @param \Throwable $exception the exception to be rendered.
*/
abstract protected function renderException($exception);
/**
* Logs the given exception.
* @param \Throwable $exception the exception to be logged
* @since 2.0.3 this method is now public.
*/
public function logException($exception)
{
$category = get_class($exception);
if ($exception instanceof HttpException) {
$category = 'yii\\web\\HttpException:' . $exception->statusCode;
} elseif ($exception instanceof \ErrorException) {
$category .= ':' . $exception->getSeverity();
}
Yii::error($exception, $category);
}
/**
* Removes all output echoed before calling this method.
*/
public function clearOutput()
{
// 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();
}
}
}
/**
* 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 \Throwable $exception the exception to convert to a PHP error.
* @return never
*/
public static function convertExceptionToError($exception)
{
trigger_error(static::convertExceptionToString($exception), E_USER_ERROR);
}
/**
* Converts an exception into a simple string.
* @param \Throwable $exception the exception being converted
* @return string the string representation of the exception.
*/
public static function convertExceptionToString($exception)
{
if ($exception instanceof UserException) {
return "{$exception->getName()}: {$exception->getMessage()}";
}
if (YII_DEBUG) {
return static::convertExceptionToVerboseString($exception);
}
return 'An internal server error occurred.';
}
/**
* Converts an exception into a string that has verbose information about the exception and its trace.
* @param \Throwable $exception the exception being converted
* @return string the string representation of the exception.
*
* @since 2.0.14
*/
public static function convertExceptionToVerboseString($exception)
{
if ($exception instanceof Exception) {
$message = "Exception ({$exception->getName()})";
} elseif ($exception instanceof ErrorException) {
$message = (string)$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();
return $message;
}
}