1 | <?php |
||
2 | /** |
||
3 | * @link https://www.yiiframework.com/ |
||
4 | * @copyright Copyright (c) 2008 Yii Software LLC |
||
5 | * @license https://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 | 246 | public function init() |
|
76 | { |
||
77 | 246 | $this->silentExitOnException = $this->silentExitOnException !== null ? $this->silentExitOnException : YII_ENV_TEST; |
|
78 | 246 | parent::init(); |
|
79 | } |
||
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
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 | // to restore working directory in shutdown handler |
||
100 | if (PHP_SAPI !== 'cli') { |
||
101 | $this->_workingDirectory = getcwd(); |
||
102 | } |
||
103 | register_shutdown_function([$this, 'handleFatalError']); |
||
104 | $this->_registered = true; |
||
105 | } |
||
106 | } |
||
107 | |||
108 | /** |
||
109 | * Unregisters this error handler by restoring the PHP error and exception handlers. |
||
110 | * @since 2.0.32 this will not do anything if the error handler was not registered |
||
111 | */ |
||
112 | public function unregister() |
||
113 | { |
||
114 | if ($this->_registered) { |
||
115 | $this->_memoryReserve = null; |
||
116 | $this->_workingDirectory = null; |
||
117 | restore_error_handler(); |
||
118 | restore_exception_handler(); |
||
119 | $this->_registered = false; |
||
120 | } |
||
121 | } |
||
122 | |||
123 | /** |
||
124 | * Handles uncaught PHP exceptions. |
||
125 | * |
||
126 | * This method is implemented as a PHP exception handler. |
||
127 | * |
||
128 | * @param \Throwable $exception the exception that is not caught |
||
129 | */ |
||
130 | public function handleException($exception) |
||
131 | { |
||
132 | if ($exception instanceof ExitException) { |
||
133 | return; |
||
134 | } |
||
135 | |||
136 | $this->exception = $exception; |
||
137 | |||
138 | // disable error capturing to avoid recursive errors while handling exceptions |
||
139 | $this->unregister(); |
||
140 | |||
141 | // set preventive HTTP status code to 500 in case error handling somehow fails and headers are sent |
||
142 | // HTTP exceptions will override this value in renderException() |
||
143 | if (PHP_SAPI !== 'cli') { |
||
144 | http_response_code(500); |
||
145 | } |
||
146 | |||
147 | try { |
||
148 | $this->logException($exception); |
||
149 | if ($this->discardExistingOutput) { |
||
150 | $this->clearOutput(); |
||
151 | } |
||
152 | $this->renderException($exception); |
||
153 | if (!$this->silentExitOnException) { |
||
154 | \Yii::getLogger()->flush(true); |
||
155 | if (defined('HHVM_VERSION')) { |
||
156 | flush(); |
||
157 | } |
||
158 | exit(1); |
||
159 | } |
||
160 | } catch (\Exception $e) { |
||
161 | // an other exception could be thrown while displaying the exception |
||
162 | $this->handleFallbackExceptionMessage($e, $exception); |
||
163 | } catch (\Throwable $e) { |
||
164 | // additional check for \Throwable introduced in PHP 7 |
||
165 | $this->handleFallbackExceptionMessage($e, $exception); |
||
166 | } |
||
167 | |||
168 | $this->exception = null; |
||
169 | } |
||
170 | |||
171 | /** |
||
172 | * Handles exception thrown during exception processing in [[handleException()]]. |
||
173 | * @param \Throwable $exception Exception that was thrown during main exception processing. |
||
174 | * @param \Throwable $previousException Main exception processed in [[handleException()]]. |
||
175 | * @since 2.0.11 |
||
176 | */ |
||
177 | protected function handleFallbackExceptionMessage($exception, $previousException) |
||
178 | { |
||
179 | $msg = "An Error occurred while handling another error:\n"; |
||
180 | $msg .= (string) $exception; |
||
181 | $msg .= "\nPrevious exception:\n"; |
||
182 | $msg .= (string) $previousException; |
||
183 | if (YII_DEBUG) { |
||
184 | if (PHP_SAPI === 'cli') { |
||
185 | echo $msg . "\n"; |
||
186 | } else { |
||
187 | echo '<pre>' . htmlspecialchars($msg, ENT_QUOTES, Yii::$app->charset) . '</pre>'; |
||
188 | } |
||
189 | $msg .= "\n\$_SERVER = " . VarDumper::export($_SERVER); |
||
190 | } else { |
||
191 | echo 'An internal server error occurred.'; |
||
192 | } |
||
193 | error_log($msg); |
||
194 | if (defined('HHVM_VERSION')) { |
||
195 | flush(); |
||
196 | } |
||
197 | exit(1); |
||
198 | } |
||
199 | |||
200 | /** |
||
201 | * Handles HHVM execution errors such as warnings and notices. |
||
202 | * |
||
203 | * This method is used as a HHVM error handler. It will store exception that will |
||
204 | * be used in fatal error handler |
||
205 | * |
||
206 | * @param int $code the level of the error raised. |
||
207 | * @param string $message the error message. |
||
208 | * @param string $file the filename that the error was raised in. |
||
209 | * @param int $line the line number the error was raised at. |
||
210 | * @param mixed $context |
||
211 | * @param mixed $backtrace trace of error |
||
212 | * @return bool whether the normal error handler continues. |
||
213 | * |
||
214 | * @throws ErrorException |
||
215 | * @since 2.0.6 |
||
216 | */ |
||
217 | public function handleHhvmError($code, $message, $file, $line, $context, $backtrace) |
||
218 | { |
||
219 | if ($this->handleError($code, $message, $file, $line)) { |
||
220 | return true; |
||
221 | } |
||
222 | if (E_ERROR & $code) { |
||
223 | $exception = new ErrorException($message, $code, $code, $file, $line); |
||
224 | $ref = new \ReflectionProperty('\Exception', 'trace'); |
||
225 | $ref->setAccessible(true); |
||
226 | $ref->setValue($exception, $backtrace); |
||
227 | $this->_hhvmException = $exception; |
||
228 | } |
||
229 | |||
230 | return false; |
||
231 | } |
||
232 | |||
233 | /** |
||
234 | * Handles PHP execution errors such as warnings and notices. |
||
235 | * |
||
236 | * This method is used as a PHP error handler. It will simply raise an [[ErrorException]]. |
||
237 | * |
||
238 | * @param int $code the level of the error raised. |
||
239 | * @param string $message the error message. |
||
240 | * @param string $file the filename that the error was raised in. |
||
241 | * @param int $line the line number the error was raised at. |
||
242 | * @return bool whether the normal error handler continues. |
||
243 | * |
||
244 | * @throws ErrorException |
||
245 | */ |
||
246 | public function handleError($code, $message, $file, $line) |
||
247 | { |
||
248 | if (error_reporting() & $code) { |
||
249 | // load ErrorException manually here because autoloading them will not work |
||
250 | // when error occurs while autoloading a class |
||
251 | if (!class_exists('yii\\base\\ErrorException', false)) { |
||
252 | require_once __DIR__ . '/ErrorException.php'; |
||
253 | } |
||
254 | $exception = new ErrorException($message, $code, $code, $file, $line); |
||
255 | |||
256 | if (PHP_VERSION_ID < 70400) { |
||
257 | // prior to PHP 7.4 we can't throw exceptions inside of __toString() - it will result a fatal error |
||
258 | $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); |
||
259 | array_shift($trace); |
||
260 | foreach ($trace as $frame) { |
||
261 | if ($frame['function'] === '__toString') { |
||
262 | $this->handleException($exception); |
||
263 | if (defined('HHVM_VERSION')) { |
||
264 | flush(); |
||
265 | } |
||
266 | exit(1); |
||
267 | } |
||
268 | } |
||
269 | } |
||
270 | |||
271 | throw $exception; |
||
272 | } |
||
273 | |||
274 | return false; |
||
275 | } |
||
276 | |||
277 | /** |
||
278 | * Handles fatal PHP errors. |
||
279 | */ |
||
280 | public function handleFatalError() |
||
281 | { |
||
282 | unset($this->_memoryReserve); |
||
283 | |||
284 | if (isset($this->_workingDirectory)) { |
||
285 | // fix working directory for some Web servers e.g. Apache |
||
286 | chdir($this->_workingDirectory); |
||
287 | // flush memory |
||
288 | unset($this->_workingDirectory); |
||
289 | } |
||
290 | |||
291 | $error = error_get_last(); |
||
292 | if ($error === null) { |
||
293 | return; |
||
294 | } |
||
295 | |||
296 | // load ErrorException manually here because autoloading them will not work |
||
297 | // when error occurs while autoloading a class |
||
298 | if (!class_exists('yii\\base\\ErrorException', false)) { |
||
299 | require_once __DIR__ . '/ErrorException.php'; |
||
300 | } |
||
301 | if (!ErrorException::isFatalError($error)) { |
||
302 | return; |
||
303 | } |
||
304 | |||
305 | if (!empty($this->_hhvmException)) { |
||
306 | $this->exception = $this->_hhvmException; |
||
307 | } else { |
||
308 | $this->exception = new ErrorException( |
||
309 | $error['message'], |
||
310 | $error['type'], |
||
311 | $error['type'], |
||
312 | $error['file'], |
||
313 | $error['line'] |
||
314 | ); |
||
315 | } |
||
316 | unset($error); |
||
317 | |||
318 | $this->logException($this->exception); |
||
319 | |||
320 | if ($this->discardExistingOutput) { |
||
321 | $this->clearOutput(); |
||
322 | } |
||
323 | $this->renderException($this->exception); |
||
324 | |||
325 | // need to explicitly flush logs because exit() next will terminate the app immediately |
||
326 | Yii::getLogger()->flush(true); |
||
327 | if (defined('HHVM_VERSION')) { |
||
328 | flush(); |
||
329 | } |
||
330 | |||
331 | $this->trigger(static::EVENT_SHUTDOWN); |
||
332 | |||
333 | // ensure it is called after user-defined shutdown functions |
||
334 | register_shutdown_function(function () { |
||
335 | exit(1); |
||
336 | }); |
||
337 | } |
||
338 | |||
339 | /** |
||
340 | * Renders the exception. |
||
341 | * @param \Throwable $exception the exception to be rendered. |
||
342 | */ |
||
343 | abstract protected function renderException($exception); |
||
344 | |||
345 | /** |
||
346 | * Logs the given exception. |
||
347 | * @param \Throwable $exception the exception to be logged |
||
348 | * @since 2.0.3 this method is now public. |
||
349 | */ |
||
350 | public function logException($exception) |
||
351 | { |
||
352 | $category = get_class($exception); |
||
353 | if ($exception instanceof HttpException) { |
||
354 | $category = 'yii\\web\\HttpException:' . $exception->statusCode; |
||
355 | } elseif ($exception instanceof \ErrorException) { |
||
356 | $category .= ':' . $exception->getSeverity(); |
||
357 | } |
||
358 | Yii::error($exception, $category); |
||
359 | } |
||
360 | |||
361 | /** |
||
362 | * Removes all output echoed before calling this method. |
||
363 | */ |
||
364 | public function clearOutput() |
||
365 | { |
||
366 | // the following manual level counting is to deal with zlib.output_compression set to On |
||
367 | for ($level = ob_get_level(); $level > 0; --$level) { |
||
368 | if (!@ob_end_clean()) { |
||
369 | ob_clean(); |
||
370 | } |
||
371 | } |
||
372 | } |
||
373 | |||
374 | /** |
||
375 | * Converts an exception into a PHP error. |
||
376 | * |
||
377 | * This method can be used to convert exceptions inside of methods like `__toString()` |
||
378 | * to PHP errors because exceptions cannot be thrown inside of them. |
||
379 | * @param \Throwable $exception the exception to convert to a PHP error. |
||
380 | * @return never |
||
381 | */ |
||
382 | public static function convertExceptionToError($exception) |
||
383 | { |
||
384 | trigger_error(static::convertExceptionToString($exception), E_USER_ERROR); |
||
385 | } |
||
386 | |||
387 | /** |
||
388 | * Converts an exception into a simple string. |
||
389 | * @param \Throwable $exception the exception being converted |
||
390 | * @return string the string representation of the exception. |
||
391 | */ |
||
392 | 1 | public static function convertExceptionToString($exception) |
|
393 | { |
||
394 | 1 | if ($exception instanceof UserException) { |
|
395 | return "{$exception->getName()}: {$exception->getMessage()}"; |
||
396 | } |
||
397 | |||
398 | 1 | if (YII_DEBUG) { |
|
399 | 1 | return static::convertExceptionToVerboseString($exception); |
|
400 | } |
||
401 | |||
402 | return 'An internal server error occurred.'; |
||
403 | } |
||
404 | |||
405 | /** |
||
406 | * Converts an exception into a string that has verbose information about the exception and its trace. |
||
407 | * @param \Throwable $exception the exception being converted |
||
408 | * @return string the string representation of the exception. |
||
409 | * |
||
410 | * @since 2.0.14 |
||
411 | */ |
||
412 | 2 | public static function convertExceptionToVerboseString($exception) |
|
413 | { |
||
414 | 2 | if ($exception instanceof Exception) { |
|
415 | $message = "Exception ({$exception->getName()})"; |
||
416 | 2 | } elseif ($exception instanceof ErrorException) { |
|
417 | $message = (string)$exception->getName(); |
||
418 | } else { |
||
419 | 2 | $message = 'Exception'; |
|
420 | } |
||
421 | 2 | $message .= " '" . get_class($exception) . "' with message '{$exception->getMessage()}' \n\nin " |
|
422 | 2 | . $exception->getFile() . ':' . $exception->getLine() . "\n\n" |
|
423 | 2 | . "Stack trace:\n" . $exception->getTraceAsString(); |
|
424 | |||
425 | 2 | return $message; |
|
426 | } |
||
427 | } |
||
428 |