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
125 protected static function report( Throwable $e ) {
126 try {
127 // Try and show the exception prettily, with the normal skin infrastructure
128 if ( $e instanceof MWException && $e->hasOverriddenHandler() ) {
129 // Delegate to MWException until all subclasses are handled by
130 // MWExceptionRenderer and MWException::report() has been
131 // removed.
132 $e->report();
133 } else {
134 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_PRETTY );
135 }
136 } catch ( Throwable $e2 ) {
137 // Exception occurred from within exception handler
138 // Show a simpler message for the original exception,
139 // don't try to invoke report()
140 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_RAW, $e2 );
141 }
142 }
143
149 private static function rollbackPrimaryChanges() {
150 if ( !MediaWikiServices::hasInstance() ) {
151 // MediaWiki isn't fully initialized yet, it's not safe to access services.
152 // This also means that there's nothing to roll back yet.
153 return;
154 }
155
156 $services = MediaWikiServices::getInstance();
157 $lbFactory = $services->peekService( 'DBLoadBalancerFactory' );
158 '@phan-var LBFactory $lbFactory'; /* @var LBFactory $lbFactory */
159 if ( !$lbFactory ) {
160 // There's no need to roll back transactions if the LBFactory is
161 // disabled or hasn't been created yet
162 return;
163 }
164
165 // Roll back DBs to avoid transaction notices. This might fail
166 // to roll back some databases due to connection issues or exceptions.
167 // However, any sensible DB driver will roll back implicitly anyway.
168 try {
169 $lbFactory->rollbackPrimaryChanges( __METHOD__ );
170 $lbFactory->flushPrimarySessions( __METHOD__ );
171 } catch ( DBError $e ) {
172 // If the DB is unreachable, rollback() will throw an error
173 // and the error report() method might need messages from the DB,
174 // which would result in an exception loop. PHP may escalate such
175 // errors to "Exception thrown without a stack frame" fatals, but
176 // it's better to be explicit here.
177 self::logException( $e, self::CAUGHT_BY_HANDLER );
178 }
179 }
180
190 public static function rollbackPrimaryChangesAndLog(
191 Throwable $e,
192 $catcher = self::CAUGHT_BY_OTHER
193 ) {
194 self::rollbackPrimaryChanges();
195
196 self::logException( $e, $catcher );
197 }
198
205 public static function handleUncaughtException( Throwable $e ) {
206 self::handleException( $e, self::CAUGHT_BY_HANDLER );
207
208 // Make sure we don't claim success on exit for CLI scripts (T177414)
209 if ( wfIsCLI() ) {
210 register_shutdown_function(
214 static function () {
215 exit( 255 );
216 }
217 );
218 }
219 }
220
236 public static function handleException( Throwable $e, $catcher = self::CAUGHT_BY_OTHER ) {
237 self::rollbackPrimaryChangesAndLog( $e, $catcher );
238 self::report( $e );
239 }
240
255 public static function handleError(
256 $level,
257 $message,
258 $file = null,
259 $line = null
260 ) {
261 // E_STRICT is deprecated since PHP 8.4 (T375707).
262 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
263 if ( defined( 'E_STRICT' ) && $level == @constant( 'E_STRICT' ) ) {
264 $level = E_USER_NOTICE;
265 }
266
267 // Map PHP error constant to a PSR-3 severity level.
268 // Avoid use of "DEBUG" or "INFO" levels, unless the
269 // error should evade error monitoring and alerts.
270 //
271 // To decide the log level, ask yourself: "Has the
272 // program's behaviour diverged from what the written
273 // code expected?"
274 //
275 // For example, use of a deprecated method or violating a strict standard
276 // has no impact on functional behaviour (Warning). On the other hand,
277 // accessing an undefined variable makes behaviour diverge from what the
278 // author intended/expected. PHP recovers from an undefined variables by
279 // yielding null and continuing execution, but it remains a change in
280 // behaviour given the null was not part of the code and is likely not
281 // accounted for.
282 switch ( $level ) {
283 case E_WARNING:
284 case E_CORE_WARNING:
285 case E_COMPILE_WARNING:
286 $prefix = 'PHP Warning: ';
287 $severity = LogLevel::ERROR;
288 break;
289 case E_NOTICE:
290 $prefix = 'PHP Notice: ';
291 $severity = LogLevel::ERROR;
292 break;
293 case E_USER_NOTICE:
294 // Used by wfWarn(), MWDebug::warning()
295 $prefix = 'PHP Notice: ';
296 $severity = LogLevel::WARNING;
297 break;
298 case E_USER_WARNING:
299 // Used by wfWarn(), MWDebug::warning()
300 $prefix = 'PHP Warning: ';
301 $severity = LogLevel::WARNING;
302 break;
303 case E_DEPRECATED:
304 $prefix = 'PHP Deprecated: ';
305 $severity = LogLevel::WARNING;
306 break;
307 case E_USER_DEPRECATED:
308 $prefix = 'PHP Deprecated: ';
309 $severity = LogLevel::WARNING;
310 $real = MWDebug::parseCallerDescription( $message );
311 if ( $real ) {
312 // Used by wfDeprecated(), MWDebug::deprecated()
313 // Apply caller offset from wfDeprecated() to the native error.
314 // This makes errors easier to aggregate and find in e.g. Kibana.
315 $file = $real['file'];
316 $line = $real['line'];
317 $message = $real['message'];
318 }
319 break;
320 default:
321 $prefix = 'PHP Unknown error: ';
322 $severity = LogLevel::ERROR;
323 break;
324 }
325
326 // @phan-suppress-next-line PhanTypeMismatchArgumentNullableInternal False positive
327 $e = new ErrorException( $prefix . $message, 0, $level, $file, $line );
328 self::logError( $e, $severity, self::CAUGHT_BY_HANDLER );
329
330 // If $propagateErrors is true return false so PHP shows/logs the error normally.
331 // Ignore $propagateErrors if track_errors is set
332 // (which means someone is counting on regular PHP error handling behavior).
333 return !( self::$propagateErrors || ini_get( 'track_errors' ) );
334 }
335
350 public static function handleFatalError() {
351 // Free reserved memory so that we have space to process OOM
352 // errors
353 self::$reservedMemory = null;
354
355 $lastError = error_get_last();
356 if ( $lastError === null ) {
357 return false;
358 }
359
360 $level = $lastError['type'];
361 $message = $lastError['message'];
362 $file = $lastError['file'];
363 $line = $lastError['line'];
364
365 if ( !in_array( $level, self::FATAL_ERROR_TYPES ) ) {
366 // Only interested in fatal errors, others should have been
367 // handled by MWExceptionHandler::handleError
368 return false;
369 }
370
371 $msgParts = [
372 '[{reqId}] {exception_url} PHP Fatal Error',
373 ( $line || $file ) ? ' from' : '',
374 $line ? " line $line" : '',
375 ( $line && $file ) ? ' of' : '',
376 $file ? " $file" : '',
377 ": $message",
378 ];
379 $msg = implode( '', $msgParts );
380
381 // Look at message to see if this is a class not found failure (Class 'foo' not found)
382 if ( preg_match( "/Class '\w+' not found/", $message ) ) {
383 // phpcs:disable Generic.Files.LineLength
384 $msg = <<<TXT
385{$msg}
386
387MediaWiki 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.
388
389Please see <a href="https://www.mediawiki.org/wiki/Download_from_Git#Fetch_external_libraries">mediawiki.org</a> for help on installing the required components.
390TXT;
391 // phpcs:enable
392 }
393
394 $e = new ErrorException( "PHP Fatal Error: {$message}", 0, $level, $file, $line );
395 $logger = LoggerFactory::getInstance( 'exception' );
396 $logger->error( $msg, self::getLogContext( $e, self::CAUGHT_BY_HANDLER ) );
397
398 return false;
399 }
400
411 public static function getRedactedTraceAsString( Throwable $e ) {
412 $from = 'from ' . $e->getFile() . '(' . $e->getLine() . ')' . "\n";
413 return $from . self::prettyPrintTrace( self::getRedactedTrace( $e ) );
414 }
415
424 public static function prettyPrintTrace( array $trace, $pad = '' ) {
425 $text = '';
426
427 $level = 0;
428 foreach ( $trace as $level => $frame ) {
429 if ( isset( $frame['file'] ) && isset( $frame['line'] ) ) {
430 $text .= "{$pad}#{$level} {$frame['file']}({$frame['line']}): ";
431 } else {
432 // 'file' and 'line' are unset for calls from C code
433 // (T57634) This matches behaviour of
434 // Throwable::getTraceAsString to instead display "[internal
435 // function]".
436 $text .= "{$pad}#{$level} [internal function]: ";
437 }
438
439 if ( isset( $frame['class'] ) && isset( $frame['type'] ) && isset( $frame['function'] ) ) {
440 $text .= $frame['class'] . $frame['type'] . $frame['function'];
441 } else {
442 $text .= $frame['function'] ?? 'NO_FUNCTION_GIVEN';
443 }
444
445 if ( isset( $frame['args'] ) ) {
446 $text .= '(' . implode( ', ', $frame['args'] ) . ")\n";
447 } else {
448 $text .= "()\n";
449 }
450 }
451
452 $level++;
453 $text .= "{$pad}#{$level} {main}";
454
455 return $text;
456 }
457
469 public static function getRedactedTrace( Throwable $e ) {
470 return static::redactTrace( $e->getTrace() );
471 }
472
483 public static function redactTrace( array $trace ) {
484 return array_map( static function ( $frame ) {
485 if ( isset( $frame['args'] ) ) {
486 $frame['args'] = array_map( 'get_debug_type', $frame['args'] );
487 }
488 return $frame;
489 }, $trace );
490 }
491
499 public static function getURL() {
500 if ( MW_ENTRY_POINT === 'cli' ) {
501 return false;
502 }
503 return WebRequest::getGlobalRequestURL();
504 }
505
516 public static function getLogMessage( Throwable $e ) {
517 $id = WebRequest::getRequestId();
518 $type = get_class( $e );
519 $message = $e->getMessage();
520 $url = self::getURL() ?: '[no req]';
521
522 if ( $e instanceof DBQueryError ) {
523 $message = "A database query error has occurred. Did you forget to run"
524 . " your application's database schema updater after upgrading"
525 . " or after adding a new extension?\n\nPlease see"
526 . " https://www.mediawiki.org/wiki/Special:MyLanguage/Manual:Upgrading and"
527 . " https://www.mediawiki.org/wiki/Special:MyLanguage/Manual:How_to_debug"
528 . " for more information.\n\n"
529 . $message;
530 }
531
532 return "[$id] $url $type: $message";
533 }
534
544 public static function getLogNormalMessage( Throwable $e ) {
545 if ( $e instanceof INormalizedException ) {
546 $message = $e->getNormalizedMessage();
547 } else {
548 $message = $e->getMessage();
549 }
550 if ( !$e instanceof ErrorException ) {
551 // ErrorException is something we use internally to represent
552 // PHP errors (runtime warnings that aren't thrown or caught),
553 // don't bother putting it in the logs. Let the log message
554 // lead with "PHP Warning: " instead (see ::handleError).
555 $message = get_class( $e ) . ": $message";
556 }
557
558 return "[{reqId}] {exception_url} $message";
559 }
560
565 public static function getPublicLogMessage( Throwable $e ) {
566 $reqId = WebRequest::getRequestId();
567 $type = get_class( $e );
568 return '[' . $reqId . '] '
569 . gmdate( 'Y-m-d H:i:s' ) . ': '
570 . 'Fatal exception of type "' . $type . '"';
571 }
572
585 public static function getLogContext( Throwable $e, $catcher = self::CAUGHT_BY_OTHER ) {
586 $context = [
587 'exception' => $e,
588 'exception_url' => self::getURL() ?: '[no req]',
589 // The reqId context key use the same familiar name and value as the top-level field
590 // provided by LogstashFormatter. However, formatters are configurable at run-time,
591 // and their top-level fields are logically separate from context keys and cannot be,
592 // substituted in a message, hence set explicitly here. For WMF users, these may feel,
593 // like the same thing due to Monolog V0 handling, which transmits "fields" and "context",
594 // in the same JSON object (after message formatting).
595 'reqId' => WebRequest::getRequestId(),
596 'caught_by' => $catcher
597 ];
598 if ( $e instanceof INormalizedException ) {
599 $context += $e->getMessageContext();
600 }
601 return $context;
602 }
603
616 public static function getStructuredExceptionData(
617 Throwable $e,
618 $catcher = self::CAUGHT_BY_OTHER
619 ) {
620 $data = [
621 'id' => WebRequest::getRequestId(),
622 'type' => get_class( $e ),
623 'file' => $e->getFile(),
624 'line' => $e->getLine(),
625 'message' => $e->getMessage(),
626 'code' => $e->getCode(),
627 'url' => self::getURL() ?: null,
628 'caught_by' => $catcher
629 ];
630
631 if ( $e instanceof ErrorException &&
632 ( error_reporting() & $e->getSeverity() ) === 0
633 ) {
634 // Flag suppressed errors
635 $data['suppressed'] = true;
636 }
637
638 if ( self::$logExceptionBacktrace ) {
639 $data['backtrace'] = self::getRedactedTrace( $e );
640 }
641
642 $previous = $e->getPrevious();
643 if ( $previous !== null ) {
644 $data['previous'] = self::getStructuredExceptionData( $previous, $catcher );
645 }
646
647 return $data;
648 }
649
704 public static function jsonSerializeException(
705 Throwable $e,
706 $pretty = false,
707 $escaping = 0,
708 $catcher = self::CAUGHT_BY_OTHER
709 ) {
710 return FormatJson::encode(
711 self::getStructuredExceptionData( $e, $catcher ),
712 $pretty,
713 $escaping
714 );
715 }
716
728 public static function logException(
729 Throwable $e,
730 $catcher = self::CAUGHT_BY_OTHER,
731 $extraData = []
732 ) {
733 if ( !( $e instanceof MWException ) || $e->isLoggable() ) {
734 $logger = LoggerFactory::getInstance( 'exception' );
735 $context = self::getLogContext( $e, $catcher );
736 if ( $extraData ) {
737 $context['extraData'] = $extraData;
738 }
739 $logger->error(
740 self::getLogNormalMessage( $e ),
741 $context
742 );
743
744 $json = self::jsonSerializeException( $e, false, FormatJson::ALL_OK, $catcher );
745 if ( $json !== false ) {
746 $logger = LoggerFactory::getInstance( 'exception-json' );
747 $logger->error( $json, [ 'private' => true ] );
748 }
749
750 self::callLogExceptionHook( $e, false );
751 }
752 }
753
761 private static function logError(
762 ErrorException $e,
763 $level,
764 $catcher
765 ) {
766 // The set_error_handler callback is independent from error_reporting.
767 $suppressed = ( error_reporting() & $e->getSeverity() ) === 0;
768 if ( $suppressed ) {
769 // Instead of discarding these entirely, give some visibility (but only
770 // when debugging) to errors that were intentionally silenced via
771 // the error silencing operator (@) or Wikimedia\AtEase.
772 // To avoid clobbering Logstash results, set the level to DEBUG
773 // and also send them to a dedicated channel (T193472).
774 $channel = 'silenced-error';
775 $level = LogLevel::DEBUG;
776 } else {
777 $channel = 'error';
778 }
779 $logger = LoggerFactory::getInstance( $channel );
780 $logger->log(
781 $level,
782 self::getLogNormalMessage( $e ),
783 self::getLogContext( $e, $catcher )
784 );
785
786 self::callLogExceptionHook( $e, $suppressed );
787 }
788
795 private static function callLogExceptionHook( Throwable $e, bool $suppressed ) {
796 try {
797 // It's possible for the exception handler to be triggered during service container
798 // initialization, e.g. if an autoloaded file triggers deprecation warnings.
799 // To avoid a difficult-to-debug autoload loop, avoid attempting to initialize the service
800 // container here. (T380456).
801 if ( !MediaWikiServices::hasInstance() ) {
802 return;
803 }
804
805 ( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )
806 ->onLogException( $e, $suppressed );
807 } catch ( RecursiveServiceDependencyException $e ) {
808 // An error from the HookContainer wiring will lead here (T379125)
809 }
810 }
811}
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.