MediaWiki master
MWExceptionHandler.php
Go to the documentation of this file.
1<?php
27use Psr\Log\LogLevel;
28use Wikimedia\NormalizedException\INormalizedException;
32use Wikimedia\Services\RecursiveServiceDependencyException;
33
40 public const CAUGHT_BY_HANDLER = 'mwe_handler';
42 public const CAUGHT_BY_ENTRYPOINT = 'entrypoint';
44 public const CAUGHT_BY_OTHER = 'other';
45
47 protected static $reservedMemory;
48
57 private const FATAL_ERROR_TYPES = [
58 E_ERROR,
59 E_PARSE,
60 E_CORE_ERROR,
61 E_COMPILE_ERROR,
62 E_USER_ERROR,
63
64 // E.g. "Catchable fatal error: Argument X must be Y, null given"
65 E_RECOVERABLE_ERROR,
66 ];
67
73 private static $logExceptionBacktrace = true;
74
80 private static $propagateErrors;
81
89 public static function installHandler(
90 bool $logExceptionBacktrace = true,
91 bool $propagateErrors = true
92 ) {
93 self::$logExceptionBacktrace = $logExceptionBacktrace;
94 self::$propagateErrors = $propagateErrors;
95
96 // This catches:
97 // * Exception objects that were explicitly thrown but not
98 // caught anywhere in the application. This is rare given those
99 // would normally be caught at a high-level like MediaWiki::run (index.php),
100 // api.php, or ResourceLoader::respond (load.php). These high-level
101 // catch clauses would then call MWExceptionHandler::logException
102 // or MWExceptionHandler::handleException.
103 // If they are not caught, then they are handled here.
104 // * Error objects for issues that would historically
105 // cause fatal errors but may now be caught as Throwable (not Exception).
106 // Same as previous case, but more common to bubble to here instead of
107 // caught locally because they tend to not be safe to recover from.
108 // (e.g. argument TypeError, division by zero, etc.)
109 set_exception_handler( [ self::class, 'handleUncaughtException' ] );
110
111 // This catches recoverable errors (e.g. PHP Notice, PHP Warning, PHP Error) that do not
112 // interrupt execution in any way. We log these in the background and then continue execution.
113 set_error_handler( [ self::class, 'handleError' ] );
114
115 // This catches fatal errors for which no Throwable is thrown,
116 // including Out-Of-Memory and Timeout fatals.
117 // Reserve 16k of memory so we can report OOM fatals.
118 self::$reservedMemory = str_repeat( ' ', 16384 );
119 register_shutdown_function( [ self::class, 'handleFatalError' ] );
120 }
121
126 protected static function report( Throwable $e ) {
127 try {
128 // Try and show the exception prettily, with the normal skin infrastructure
129 if ( $e instanceof MWException && $e->hasOverriddenHandler() ) {
130 // Delegate to MWException until all subclasses are handled by
131 // MWExceptionRenderer and MWException::report() has been
132 // removed.
133 $e->report();
134 } else {
135 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_PRETTY );
136 }
137 } catch ( Throwable $e2 ) {
138 // Exception occurred from within exception handler
139 // Show a simpler message for the original exception,
140 // don't try to invoke report()
141 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_RAW, $e2 );
142 }
143 }
144
150 private static function rollbackPrimaryChanges() {
151 if ( !MediaWikiServices::hasInstance() ) {
152 // MediaWiki isn't fully initialized yet, it's not safe to access services.
153 // This also means that there's nothing to roll back yet.
154 return;
155 }
156
157 $services = MediaWikiServices::getInstance();
158 $lbFactory = $services->peekService( 'DBLoadBalancerFactory' );
159 '@phan-var LBFactory $lbFactory'; /* @var LBFactory $lbFactory */
160 if ( !$lbFactory ) {
161 // There's no need to roll back transactions if the LBFactory is
162 // disabled or hasn't been created yet
163 return;
164 }
165
166 // Roll back DBs to avoid transaction notices. This might fail
167 // to roll back some databases due to connection issues or exceptions.
168 // However, any sensible DB driver will roll back implicitly anyway.
169 try {
170 $lbFactory->rollbackPrimaryChanges( __METHOD__ );
171 $lbFactory->flushPrimarySessions( __METHOD__ );
172 } catch ( DBError $e ) {
173 // If the DB is unreachable, rollback() will throw an error
174 // and the error report() method might need messages from the DB,
175 // which would result in an exception loop. PHP may escalate such
176 // errors to "Exception thrown without a stack frame" fatals, but
177 // it's better to be explicit here.
178 self::logException( $e, self::CAUGHT_BY_HANDLER );
179 }
180 }
181
191 public static function rollbackPrimaryChangesAndLog(
192 Throwable $e,
193 $catcher = self::CAUGHT_BY_OTHER
194 ) {
195 self::rollbackPrimaryChanges();
196
197 self::logException( $e, $catcher );
198 }
199
206 public static function handleUncaughtException( Throwable $e ) {
207 self::handleException( $e, self::CAUGHT_BY_HANDLER );
208
209 // Make sure we don't claim success on exit for CLI scripts (T177414)
210 if ( wfIsCLI() ) {
211 register_shutdown_function(
215 static function () {
216 exit( 255 );
217 }
218 );
219 }
220 }
221
237 public static function handleException( Throwable $e, $catcher = self::CAUGHT_BY_OTHER ) {
238 self::rollbackPrimaryChangesAndLog( $e, $catcher );
239 self::report( $e );
240 }
241
256 public static function handleError(
257 $level,
258 $message,
259 $file = null,
260 $line = null
261 ) {
262 // Map PHP error constant to a PSR-3 severity level.
263 // Avoid use of "DEBUG" or "INFO" levels, unless the
264 // error should evade error monitoring and alerts.
265 //
266 // To decide the log level, ask yourself: "Has the
267 // program's behaviour diverged from what the written
268 // code expected?"
269 //
270 // For example, use of a deprecated method or violating a strict standard
271 // has no impact on functional behaviour (Warning). On the other hand,
272 // accessing an undefined variable makes behaviour diverge from what the
273 // author intended/expected. PHP recovers from an undefined variables by
274 // yielding null and continuing execution, but it remains a change in
275 // behaviour given the null was not part of the code and is likely not
276 // accounted for.
277 switch ( $level ) {
278 case E_WARNING:
279 case E_CORE_WARNING:
280 case E_COMPILE_WARNING:
281 $prefix = 'PHP Warning: ';
282 $severity = LogLevel::ERROR;
283 break;
284 case E_NOTICE:
285 $prefix = 'PHP Notice: ';
286 $severity = LogLevel::ERROR;
287 break;
288 case E_USER_NOTICE:
289 // Used by wfWarn(), MWDebug::warning()
290 $prefix = 'PHP Notice: ';
291 $severity = LogLevel::WARNING;
292 break;
293 case E_USER_WARNING:
294 // Used by wfWarn(), MWDebug::warning()
295 $prefix = 'PHP Warning: ';
296 $severity = LogLevel::WARNING;
297 break;
298 case E_STRICT:
299 $prefix = 'PHP Strict Standards: ';
300 $severity = LogLevel::WARNING;
301 break;
302 case E_DEPRECATED:
303 $prefix = 'PHP Deprecated: ';
304 $severity = LogLevel::WARNING;
305 break;
306 case E_USER_DEPRECATED:
307 $prefix = 'PHP Deprecated: ';
308 $severity = LogLevel::WARNING;
309 $real = MWDebug::parseCallerDescription( $message );
310 if ( $real ) {
311 // Used by wfDeprecated(), MWDebug::deprecated()
312 // Apply caller offset from wfDeprecated() to the native error.
313 // This makes errors easier to aggregate and find in e.g. Kibana.
314 $file = $real['file'];
315 $line = $real['line'];
316 $message = $real['message'];
317 }
318 break;
319 default:
320 $prefix = 'PHP Unknown error: ';
321 $severity = LogLevel::ERROR;
322 break;
323 }
324
325 // @phan-suppress-next-line PhanTypeMismatchArgumentNullableInternal False positive
326 $e = new ErrorException( $prefix . $message, 0, $level, $file, $line );
327 self::logError( $e, $severity, self::CAUGHT_BY_HANDLER );
328
329 // If $propagateErrors is true return false so PHP shows/logs the error normally.
330 // Ignore $propagateErrors if track_errors is set
331 // (which means someone is counting on regular PHP error handling behavior).
332 return !( self::$propagateErrors || ini_get( 'track_errors' ) );
333 }
334
349 public static function handleFatalError() {
350 // Free reserved memory so that we have space to process OOM
351 // errors
352 self::$reservedMemory = null;
353
354 $lastError = error_get_last();
355 if ( $lastError === null ) {
356 return false;
357 }
358
359 $level = $lastError['type'];
360 $message = $lastError['message'];
361 $file = $lastError['file'];
362 $line = $lastError['line'];
363
364 if ( !in_array( $level, self::FATAL_ERROR_TYPES ) ) {
365 // Only interested in fatal errors, others should have been
366 // handled by MWExceptionHandler::handleError
367 return false;
368 }
369
370 $msgParts = [
371 '[{reqId}] {exception_url} PHP Fatal Error',
372 ( $line || $file ) ? ' from' : '',
373 $line ? " line $line" : '',
374 ( $line && $file ) ? ' of' : '',
375 $file ? " $file" : '',
376 ": $message",
377 ];
378 $msg = implode( '', $msgParts );
379
380 // Look at message to see if this is a class not found failure (Class 'foo' not found)
381 if ( preg_match( "/Class '\w+' not found/", $message ) ) {
382 // phpcs:disable Generic.Files.LineLength
383 $msg = <<<TXT
384{$msg}
385
386MediaWiki or an installed extension requires this class but it is not embedded directly in MediaWiki's git repository and must be installed separately by the end user.
387
388Please see <a href="https://www.mediawiki.org/wiki/Download_from_Git#Fetch_external_libraries">mediawiki.org</a> for help on installing the required components.
389TXT;
390 // phpcs:enable
391 }
392
393 $e = new ErrorException( "PHP Fatal Error: {$message}", 0, $level, $file, $line );
394 $logger = LoggerFactory::getInstance( 'exception' );
395 $logger->error( $msg, self::getLogContext( $e, self::CAUGHT_BY_HANDLER ) );
396
397 return false;
398 }
399
410 public static function getRedactedTraceAsString( Throwable $e ) {
411 $from = 'from ' . $e->getFile() . '(' . $e->getLine() . ')' . "\n";
412 return $from . self::prettyPrintTrace( self::getRedactedTrace( $e ) );
413 }
414
423 public static function prettyPrintTrace( array $trace, $pad = '' ) {
424 $text = '';
425
426 $level = 0;
427 foreach ( $trace as $level => $frame ) {
428 if ( isset( $frame['file'] ) && isset( $frame['line'] ) ) {
429 $text .= "{$pad}#{$level} {$frame['file']}({$frame['line']}): ";
430 } else {
431 // 'file' and 'line' are unset for calls from C code
432 // (T57634) This matches behaviour of
433 // Throwable::getTraceAsString to instead display "[internal
434 // function]".
435 $text .= "{$pad}#{$level} [internal function]: ";
436 }
437
438 if ( isset( $frame['class'] ) && isset( $frame['type'] ) && isset( $frame['function'] ) ) {
439 $text .= $frame['class'] . $frame['type'] . $frame['function'];
440 } else {
441 $text .= $frame['function'] ?? 'NO_FUNCTION_GIVEN';
442 }
443
444 if ( isset( $frame['args'] ) ) {
445 $text .= '(' . implode( ', ', $frame['args'] ) . ")\n";
446 } else {
447 $text .= "()\n";
448 }
449 }
450
451 $level++;
452 $text .= "{$pad}#{$level} {main}";
453
454 return $text;
455 }
456
468 public static function getRedactedTrace( Throwable $e ) {
469 return static::redactTrace( $e->getTrace() );
470 }
471
482 public static function redactTrace( array $trace ) {
483 return array_map( static function ( $frame ) {
484 if ( isset( $frame['args'] ) ) {
485 $frame['args'] = array_map( 'get_debug_type', $frame['args'] );
486 }
487 return $frame;
488 }, $trace );
489 }
490
498 public static function getURL() {
499 if ( MW_ENTRY_POINT === 'cli' ) {
500 return false;
501 }
502 return WebRequest::getGlobalRequestURL();
503 }
504
515 public static function getLogMessage( Throwable $e ) {
516 $id = WebRequest::getRequestId();
517 $type = get_class( $e );
518 $message = $e->getMessage();
519 $url = self::getURL() ?: '[no req]';
520
521 if ( $e instanceof DBQueryError ) {
522 $message = "A database query error has occurred. Did you forget to run"
523 . " your application's database schema updater after upgrading"
524 . " or after adding a new extension?\n\nPlease see"
525 . " https://www.mediawiki.org/wiki/Special:MyLanguage/Manual:Upgrading and"
526 . " https://www.mediawiki.org/wiki/Special:MyLanguage/Manual:How_to_debug"
527 . " for more information.\n\n"
528 . $message;
529 }
530
531 return "[$id] $url $type: $message";
532 }
533
543 public static function getLogNormalMessage( Throwable $e ) {
544 if ( $e instanceof INormalizedException ) {
545 $message = $e->getNormalizedMessage();
546 } else {
547 $message = $e->getMessage();
548 }
549 if ( !$e instanceof ErrorException ) {
550 // ErrorException is something we use internally to represent
551 // PHP errors (runtime warnings that aren't thrown or caught),
552 // don't bother putting it in the logs. Let the log message
553 // lead with "PHP Warning: " instead (see ::handleError).
554 $message = get_class( $e ) . ": $message";
555 }
556
557 return "[{reqId}] {exception_url} $message";
558 }
559
564 public static function getPublicLogMessage( Throwable $e ) {
565 $reqId = WebRequest::getRequestId();
566 $type = get_class( $e );
567 return '[' . $reqId . '] '
568 . gmdate( 'Y-m-d H:i:s' ) . ': '
569 . 'Fatal exception of type "' . $type . '"';
570 }
571
584 public static function getLogContext( Throwable $e, $catcher = self::CAUGHT_BY_OTHER ) {
585 $context = [
586 'exception' => $e,
587 'exception_url' => self::getURL() ?: '[no req]',
588 // The reqId context key use the same familiar name and value as the top-level field
589 // provided by LogstashFormatter. However, formatters are configurable at run-time,
590 // and their top-level fields are logically separate from context keys and cannot be,
591 // substituted in a message, hence set explicitly here. For WMF users, these may feel,
592 // like the same thing due to Monolog V0 handling, which transmits "fields" and "context",
593 // in the same JSON object (after message formatting).
594 'reqId' => WebRequest::getRequestId(),
595 'caught_by' => $catcher
596 ];
597 if ( $e instanceof INormalizedException ) {
598 $context += $e->getMessageContext();
599 }
600 return $context;
601 }
602
615 public static function getStructuredExceptionData(
616 Throwable $e,
617 $catcher = self::CAUGHT_BY_OTHER
618 ) {
619 $data = [
620 'id' => WebRequest::getRequestId(),
621 'type' => get_class( $e ),
622 'file' => $e->getFile(),
623 'line' => $e->getLine(),
624 'message' => $e->getMessage(),
625 'code' => $e->getCode(),
626 'url' => self::getURL() ?: null,
627 'caught_by' => $catcher
628 ];
629
630 if ( $e instanceof ErrorException &&
631 ( error_reporting() & $e->getSeverity() ) === 0
632 ) {
633 // Flag suppressed errors
634 $data['suppressed'] = true;
635 }
636
637 if ( self::$logExceptionBacktrace ) {
638 $data['backtrace'] = self::getRedactedTrace( $e );
639 }
640
641 $previous = $e->getPrevious();
642 if ( $previous !== null ) {
643 $data['previous'] = self::getStructuredExceptionData( $previous, $catcher );
644 }
645
646 return $data;
647 }
648
703 public static function jsonSerializeException(
704 Throwable $e,
705 $pretty = false,
706 $escaping = 0,
707 $catcher = self::CAUGHT_BY_OTHER
708 ) {
709 return FormatJson::encode(
710 self::getStructuredExceptionData( $e, $catcher ),
711 $pretty,
712 $escaping
713 );
714 }
715
727 public static function logException(
728 Throwable $e,
729 $catcher = self::CAUGHT_BY_OTHER,
730 $extraData = []
731 ) {
732 if ( !( $e instanceof MWException ) || $e->isLoggable() ) {
733 $logger = LoggerFactory::getInstance( 'exception' );
734 $context = self::getLogContext( $e, $catcher );
735 if ( $extraData ) {
736 $context['extraData'] = $extraData;
737 }
738 $logger->error(
739 self::getLogNormalMessage( $e ),
740 $context
741 );
742
743 $json = self::jsonSerializeException( $e, false, FormatJson::ALL_OK, $catcher );
744 if ( $json !== false ) {
745 $logger = LoggerFactory::getInstance( 'exception-json' );
746 $logger->error( $json, [ 'private' => true ] );
747 }
748
749 self::callLogExceptionHook( $e, false );
750 }
751 }
752
760 private static function logError(
761 ErrorException $e,
762 $level,
763 $catcher
764 ) {
765 // The set_error_handler callback is independent from error_reporting.
766 $suppressed = ( error_reporting() & $e->getSeverity() ) === 0;
767 if ( $suppressed ) {
768 // Instead of discarding these entirely, give some visibility (but only
769 // when debugging) to errors that were intentionally silenced via
770 // the error silencing operator (@) or Wikimedia\AtEase.
771 // To avoid clobbering Logstash results, set the level to DEBUG
772 // and also send them to a dedicated channel (T193472).
773 $channel = 'silenced-error';
774 $level = LogLevel::DEBUG;
775 } else {
776 $channel = 'error';
777 }
778 $logger = LoggerFactory::getInstance( $channel );
779 $logger->log(
780 $level,
781 self::getLogNormalMessage( $e ),
782 self::getLogContext( $e, $catcher )
783 );
784
785 self::callLogExceptionHook( $e, $suppressed );
786 }
787
794 private static function callLogExceptionHook( Throwable $e, bool $suppressed ) {
795 try {
796 ( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )
797 ->onLogException( $e, $suppressed );
798 } catch ( RecursiveServiceDependencyException $e ) {
799 // An error from the HookContainer wiring will lead here (T379125)
800 }
801 }
802}
wfIsCLI()
Check if we are running from the commandline.
const MW_ENTRY_POINT
Definition api.php:35
Handler class for MWExceptions.
static getLogContext(Throwable $e, $catcher=self::CAUGHT_BY_OTHER)
Get a PSR-3 log event context from a Throwable.
const CAUGHT_BY_HANDLER
Error caught and reported by this exception handler.
static handleError( $level, $message, $file=null, $line=null)
Handler for set_error_handler() callback notifications.
static rollbackPrimaryChangesAndLog(Throwable $e, $catcher=self::CAUGHT_BY_OTHER)
Roll back any open database transactions and log the stack trace of the throwable.
static installHandler(bool $logExceptionBacktrace=true, bool $propagateErrors=true)
Install handlers with PHP.
const CAUGHT_BY_OTHER
Error reported by direct logException() call.
static getStructuredExceptionData(Throwable $e, $catcher=self::CAUGHT_BY_OTHER)
Get a structured representation of a Throwable.
static getRedactedTraceAsString(Throwable $e)
Generate a string representation of a throwable's stack trace.
static report(Throwable $e)
Report a throwable to the user.
static logException(Throwable $e, $catcher=self::CAUGHT_BY_OTHER, $extraData=[])
Log a throwable to the exception log (if enabled).
static getPublicLogMessage(Throwable $e)
static getRedactedTrace(Throwable $e)
Return a copy of a throwable's backtrace as an array.
static handleUncaughtException(Throwable $e)
Callback to use with PHP's set_exception_handler.
static prettyPrintTrace(array $trace, $pad='')
Generate a string representation of a stacktrace.
static string null $reservedMemory
static jsonSerializeException(Throwable $e, $pretty=false, $escaping=0, $catcher=self::CAUGHT_BY_OTHER)
Serialize a Throwable object to JSON.
static getLogMessage(Throwable $e)
Get a message formatting the throwable message and its origin.
const CAUGHT_BY_ENTRYPOINT
Error caught and reported by a script entry point.
static redactTrace(array $trace)
Redact a stacktrace generated by Throwable::getTrace(), debug_backtrace() or similar means.
static handleFatalError()
Callback used as a registered shutdown function.
static getLogNormalMessage(Throwable $e)
Get a normalised message for formatting with PSR-3 log event context.
static getURL()
If the exception occurred in the course of responding to a request, returns the requested URL.
static handleException(Throwable $e, $catcher=self::CAUGHT_BY_OTHER)
Exception handler which simulates the appropriate catch() handling:
MediaWiki exception.
Debug toolbar.
Definition MWDebug.php:49
This class provides an implementation of the core hook interfaces, forwarding hook calls to HookConta...
JSON formatter wrapper class.
Create PSR-3 logger objects.
Service locator for MediaWiki core services.
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form,...
Database error base class.
Definition DBError.php:36
A helper class for throttling authentication attempts.