MediaWiki master
MWExceptionHandler.php
Go to the documentation of this file.
1<?php
25use Psr\Log\LogLevel;
26use Wikimedia\NormalizedException\INormalizedException;
29
36 public const CAUGHT_BY_HANDLER = 'mwe_handler';
38 public const CAUGHT_BY_ENTRYPOINT = 'entrypoint';
40 public const CAUGHT_BY_OTHER = 'other';
41
43 protected static $reservedMemory;
44
55 protected static $fatalErrorTypes = [
56 E_ERROR,
57 E_PARSE,
58 E_CORE_ERROR,
59 E_COMPILE_ERROR,
60 E_USER_ERROR,
61
62 // E.g. "Catchable fatal error: Argument X must be Y, null given"
63 E_RECOVERABLE_ERROR,
64 ];
65
71 private static $logExceptionBacktrace = true;
72
78 private static $propagateErrors;
79
87 public static function installHandler(
88 bool $logExceptionBacktrace = true,
89 bool $propagateErrors = true
90 ) {
91 self::$logExceptionBacktrace = $logExceptionBacktrace;
92 self::$propagateErrors = $propagateErrors;
93
94 // This catches:
95 // * Exception objects that were explicitly thrown but not
96 // caught anywhere in the application. This is rare given those
97 // would normally be caught at a high-level like MediaWiki::run (index.php),
98 // api.php, or ResourceLoader::respond (load.php). These high-level
99 // catch clauses would then call MWExceptionHandler::logException
100 // or MWExceptionHandler::handleException.
101 // If they are not caught, then they are handled here.
102 // * Error objects for issues that would historically
103 // cause fatal errors but may now be caught as Throwable (not Exception).
104 // Same as previous case, but more common to bubble to here instead of
105 // caught locally because they tend to not be safe to recover from.
106 // (e.g. argument TypeError, division by zero, etc.)
107 set_exception_handler( [ self::class, 'handleUncaughtException' ] );
108
109 // This catches recoverable errors (e.g. PHP Notice, PHP Warning, PHP Error) that do not
110 // interrupt execution in any way. We log these in the background and then continue execution.
111 set_error_handler( [ self::class, 'handleError' ] );
112
113 // This catches fatal errors for which no Throwable is thrown,
114 // including Out-Of-Memory and Timeout fatals.
115 // Reserve 16k of memory so we can report OOM fatals.
116 self::$reservedMemory = str_repeat( ' ', 16384 );
117 register_shutdown_function( [ self::class, 'handleFatalError' ] );
118 }
119
124 protected static function report( Throwable $e ) {
125 try {
126 // Try and show the exception prettily, with the normal skin infrastructure
127 if ( $e instanceof MWException && $e->hasOverriddenHandler() ) {
128 // Delegate to MWException until all subclasses are handled by
129 // MWExceptionRenderer and MWException::report() has been
130 // removed.
131 $e->report();
132 } else {
133 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_PRETTY );
134 }
135 } catch ( Throwable $e2 ) {
136 // Exception occurred from within exception handler
137 // Show a simpler message for the original exception,
138 // don't try to invoke report()
139 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_RAW, $e2 );
140 }
141 }
142
148 private static function rollbackPrimaryChanges() {
149 if ( !MediaWikiServices::hasInstance() ) {
150 // MediaWiki isn't fully initialized yet, it's not safe to access services.
151 // This also means that there's nothing to roll back yet.
152 return;
153 }
154
155 $services = MediaWikiServices::getInstance();
156 if ( $services->isServiceDisabled( 'DBLoadBalancerFactory' ) ) {
157 // The DBLoadBalancerFactory is disabled, possibly because we are in the installer,
158 // or we are in the process of shutting MediaWiki. At this point, any DB transactions
159 // would already have been committed or rolled back.
160 return;
161 }
162
163 // Roll back DBs to avoid transaction notices. This might fail
164 // to roll back some databases due to connection issues or exceptions.
165 // However, any sensible DB driver will roll back implicitly anyway.
166 try {
167 $lbFactory = $services->getDBLoadBalancerFactory();
168 $lbFactory->rollbackPrimaryChanges( __METHOD__ );
169 $lbFactory->flushPrimarySessions( __METHOD__ );
170 } catch ( DBError $e ) {
171 // If the DB is unreachable, rollback() will throw an error
172 // and the error report() method might need messages from the DB,
173 // which would result in an exception loop. PHP may escalate such
174 // errors to "Exception thrown without a stack frame" fatals, but
175 // it's better to be explicit here.
176 self::logException( $e, self::CAUGHT_BY_HANDLER );
177 }
178 }
179
189 public static function rollbackPrimaryChangesAndLog(
190 Throwable $e,
191 $catcher = self::CAUGHT_BY_OTHER
192 ) {
193 self::rollbackPrimaryChanges();
194
195 self::logException( $e, $catcher );
196 }
197
204 public static function handleUncaughtException( Throwable $e ) {
205 self::handleException( $e, self::CAUGHT_BY_HANDLER );
206
207 // Make sure we don't claim success on exit for CLI scripts (T177414)
208 if ( wfIsCLI() ) {
209 register_shutdown_function(
213 static function () {
214 exit( 255 );
215 }
216 );
217 }
218 }
219
235 public static function handleException( Throwable $e, $catcher = self::CAUGHT_BY_OTHER ) {
236 self::rollbackPrimaryChangesAndLog( $e, $catcher );
237 self::report( $e );
238 }
239
254 public static function handleError(
255 $level,
256 $message,
257 $file = null,
258 $line = null
259 ) {
260 // Map PHP error constant to a PSR-3 severity level.
261 // Avoid use of "DEBUG" or "INFO" levels, unless the
262 // error should evade error monitoring and alerts.
263 //
264 // To decide the log level, ask yourself: "Has the
265 // program's behaviour diverged from what the written
266 // code expected?"
267 //
268 // For example, use of a deprecated method or violating a strict standard
269 // has no impact on functional behaviour (Warning). On the other hand,
270 // accessing an undefined variable makes behaviour diverge from what the
271 // author intended/expected. PHP recovers from an undefined variables by
272 // yielding null and continuing execution, but it remains a change in
273 // behaviour given the null was not part of the code and is likely not
274 // accounted for.
275 switch ( $level ) {
276 case E_WARNING:
277 case E_CORE_WARNING:
278 case E_COMPILE_WARNING:
279 $prefix = 'PHP Warning: ';
280 $severity = LogLevel::ERROR;
281 break;
282 case E_NOTICE:
283 $prefix = 'PHP Notice: ';
284 $severity = LogLevel::ERROR;
285 break;
286 case E_USER_NOTICE:
287 // Used by wfWarn(), MWDebug::warning()
288 $prefix = 'PHP Notice: ';
289 $severity = LogLevel::WARNING;
290 break;
291 case E_USER_WARNING:
292 // Used by wfWarn(), MWDebug::warning()
293 $prefix = 'PHP Warning: ';
294 $severity = LogLevel::WARNING;
295 break;
296 case E_STRICT:
297 $prefix = 'PHP Strict Standards: ';
298 $severity = LogLevel::WARNING;
299 break;
300 case E_DEPRECATED:
301 $prefix = 'PHP Deprecated: ';
302 $severity = LogLevel::WARNING;
303 break;
304 case E_USER_DEPRECATED:
305 $prefix = 'PHP Deprecated: ';
306 $severity = LogLevel::WARNING;
307 $real = MWDebug::parseCallerDescription( $message );
308 if ( $real ) {
309 // Used by wfDeprecated(), MWDebug::deprecated()
310 // Apply caller offset from wfDeprecated() to the native error.
311 // This makes errors easier to aggregate and find in e.g. Kibana.
312 $file = $real['file'];
313 $line = $real['line'];
314 $message = $real['message'];
315 }
316 break;
317 default:
318 $prefix = 'PHP Unknown error: ';
319 $severity = LogLevel::ERROR;
320 break;
321 }
322
323 // @phan-suppress-next-line PhanTypeMismatchArgumentNullableInternal False positive
324 $e = new ErrorException( $prefix . $message, 0, $level, $file, $line );
325 self::logError( $e, $severity, self::CAUGHT_BY_HANDLER );
326
327 // If $propagateErrors is true return false so PHP shows/logs the error normally.
328 // Ignore $propagateErrors if track_errors is set
329 // (which means someone is counting on regular PHP error handling behavior).
330 return !( self::$propagateErrors || ini_get( 'track_errors' ) );
331 }
332
347 public static function handleFatalError() {
348 // Free reserved memory so that we have space to process OOM
349 // errors
350 self::$reservedMemory = null;
351
352 $lastError = error_get_last();
353 if ( $lastError === null ) {
354 return false;
355 }
356
357 $level = $lastError['type'];
358 $message = $lastError['message'];
359 $file = $lastError['file'];
360 $line = $lastError['line'];
361
362 if ( !in_array( $level, self::$fatalErrorTypes ) ) {
363 // Only interested in fatal errors, others should have been
364 // handled by MWExceptionHandler::handleError
365 return false;
366 }
367
368 $msgParts = [
369 '[{reqId}] {exception_url} PHP Fatal Error',
370 ( $line || $file ) ? ' from' : '',
371 $line ? " line $line" : '',
372 ( $line && $file ) ? ' of' : '',
373 $file ? " $file" : '',
374 ": $message",
375 ];
376 $msg = implode( '', $msgParts );
377
378 // Look at message to see if this is a class not found failure (Class 'foo' not found)
379 if ( preg_match( "/Class '\w+' not found/", $message ) ) {
380 // phpcs:disable Generic.Files.LineLength
381 $msg = <<<TXT
382{$msg}
383
384MediaWiki 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.
385
386Please see <a href="https://www.mediawiki.org/wiki/Download_from_Git#Fetch_external_libraries">mediawiki.org</a> for help on installing the required components.
387TXT;
388 // phpcs:enable
389 }
390
391 $e = new ErrorException( "PHP Fatal Error: {$message}", 0, $level, $file, $line );
392 $logger = LoggerFactory::getInstance( 'exception' );
393 $logger->error( $msg, self::getLogContext( $e, self::CAUGHT_BY_HANDLER ) );
394
395 return false;
396 }
397
408 public static function getRedactedTraceAsString( Throwable $e ) {
409 $from = 'from ' . $e->getFile() . '(' . $e->getLine() . ')' . "\n";
410 return $from . self::prettyPrintTrace( self::getRedactedTrace( $e ) );
411 }
412
421 public static function prettyPrintTrace( array $trace, $pad = '' ) {
422 $text = '';
423
424 $level = 0;
425 foreach ( $trace as $level => $frame ) {
426 if ( isset( $frame['file'] ) && isset( $frame['line'] ) ) {
427 $text .= "{$pad}#{$level} {$frame['file']}({$frame['line']}): ";
428 } else {
429 // 'file' and 'line' are unset for calls from C code
430 // (T57634) This matches behaviour of
431 // Throwable::getTraceAsString to instead display "[internal
432 // function]".
433 $text .= "{$pad}#{$level} [internal function]: ";
434 }
435
436 if ( isset( $frame['class'] ) && isset( $frame['type'] ) && isset( $frame['function'] ) ) {
437 $text .= $frame['class'] . $frame['type'] . $frame['function'];
438 } else {
439 $text .= $frame['function'] ?? 'NO_FUNCTION_GIVEN';
440 }
441
442 if ( isset( $frame['args'] ) ) {
443 $text .= '(' . implode( ', ', $frame['args'] ) . ")\n";
444 } else {
445 $text .= "()\n";
446 }
447 }
448
449 $level++;
450 $text .= "{$pad}#{$level} {main}";
451
452 return $text;
453 }
454
466 public static function getRedactedTrace( Throwable $e ) {
467 return static::redactTrace( $e->getTrace() );
468 }
469
480 public static function redactTrace( array $trace ) {
481 return array_map( static function ( $frame ) {
482 if ( isset( $frame['args'] ) ) {
483 $frame['args'] = array_map( static function ( $arg ) {
484 return is_object( $arg ) ? get_class( $arg ) : gettype( $arg );
485 }, $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
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 ( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )->onLogException( $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 // TODO: Remove this per T193472.
787 $json = self::jsonSerializeException( $e, false, FormatJson::ALL_OK, $catcher );
788 if ( $json !== false ) {
789 $logger = LoggerFactory::getInstance( "error-json" );
790 $logger->log( $level, $json, [ 'private' => true ] );
791 }
792
793 ( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )->onLogException( $e, $suppressed );
794 }
795}
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.
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.
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 array $fatalErrorTypes
Error types that, if unhandled, are fatal to the request.
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.
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.
This class provides an implementation of the core hook interfaces, forwarding hook calls to HookConta...
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 stripping il...
Database error base class.
Definition DBError.php:36
A helper class for throttling authentication attempts.