MediaWiki REL1_39
MWExceptionHandler.php
Go to the documentation of this file.
1<?php
23use Psr\Log\LogLevel;
24use Wikimedia\NormalizedException\INormalizedException;
27
34 public const CAUGHT_BY_HANDLER = 'mwe_handler';
36 public const CAUGHT_BY_ENTRYPOINT = 'entrypoint';
38 public const CAUGHT_BY_OTHER = 'other';
39
41 protected static $reservedMemory;
42
53 protected static $fatalErrorTypes = [
54 E_ERROR,
55 E_PARSE,
56 E_CORE_ERROR,
57 E_COMPILE_ERROR,
58 E_USER_ERROR,
59
60 // E.g. "Catchable fatal error: Argument X must be Y, null given"
61 E_RECOVERABLE_ERROR,
62 ];
63
69 private static $logExceptionBacktrace = true;
70
76 private static $propagateErrors;
77
85 public static function installHandler(
86 bool $logExceptionBacktrace = true,
87 bool $propagateErrors = true
88 ) {
89 self::$logExceptionBacktrace = $logExceptionBacktrace;
90 self::$propagateErrors = $propagateErrors;
91
92 // This catches:
93 // * Exception objects that were explicitly thrown but not
94 // caught anywhere in the application. This is rare given those
95 // would normally be caught at a high-level like MediaWiki::run (index.php),
96 // api.php, or ResourceLoader::respond (load.php). These high-level
97 // catch clauses would then call MWExceptionHandler::logException
98 // or MWExceptionHandler::handleException.
99 // If they are not caught, then they are handled here.
100 // * Error objects for issues that would historically
101 // cause fatal errors but may now be caught as Throwable (not Exception).
102 // Same as previous case, but more common to bubble to here instead of
103 // caught locally because they tend to not be safe to recover from.
104 // (e.g. argument TypeError, division by zero, etc.)
105 set_exception_handler( 'MWExceptionHandler::handleUncaughtException' );
106
107 // This catches recoverable errors (e.g. PHP Notice, PHP Warning, PHP Error) that do not
108 // interrupt execution in any way. We log these in the background and then continue execution.
109 set_error_handler( 'MWExceptionHandler::handleError' );
110
111 // This catches fatal errors for which no Throwable is thrown,
112 // including Out-Of-Memory and Timeout fatals.
113 // Reserve 16k of memory so we can report OOM fatals.
114 self::$reservedMemory = str_repeat( ' ', 16384 );
115 register_shutdown_function( 'MWExceptionHandler::handleFatalError' );
116 }
117
122 protected static function report( Throwable $e ) {
123 try {
124 // Try and show the exception prettily, with the normal skin infrastructure
125 if ( $e instanceof MWException ) {
126 // Delegate to MWException until all subclasses are handled by
127 // MWExceptionRenderer and MWException::report() has been
128 // removed.
129 $e->report();
130 } else {
131 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_PRETTY );
132 }
133 } catch ( Throwable $e2 ) {
134 // Exception occurred from within exception handler
135 // Show a simpler message for the original exception,
136 // don't try to invoke report()
137 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_RAW, $e2 );
138 }
139 }
140
146 private static function rollbackPrimaryChanges() {
147 if ( !MediaWikiServices::hasInstance() ) {
148 // MediaWiki isn't fully initialized yet, it's not safe to access services.
149 // This also means that there's nothing to roll back yet.
150 return;
151 }
152
153 $services = MediaWikiServices::getInstance();
154 if ( $services->isServiceDisabled( 'DBLoadBalancerFactory' ) ) {
155 // The DBLoadBalancerFactory is disabled, possibly because we are in the installer,
156 // or we are in the process of shutting MediaWiki. At this point, any DB transactions
157 // would already have been committed or rolled back.
158 return;
159 }
160
161 // Roll back DBs to avoid transaction notices. This might fail
162 // to roll back some databases due to connection issues or exceptions.
163 // However, any sensible DB driver will roll back implicitly anyway.
164 try {
165 $lbFactory = $services->getDBLoadBalancerFactory();
166 $lbFactory->rollbackPrimaryChanges( __METHOD__ );
167 $lbFactory->flushPrimarySessions( __METHOD__ );
168 } catch ( DBError $e ) {
169 // If the DB is unreachable, rollback() will throw an error
170 // and the error report() method might need messages from the DB,
171 // which would result in an exception loop. PHP may escalate such
172 // errors to "Exception thrown without a stack frame" fatals, but
173 // it's better to be explicit here.
174 self::logException( $e, self::CAUGHT_BY_HANDLER );
175 }
176 }
177
187 public static function rollbackPrimaryChangesAndLog(
188 Throwable $e,
189 $catcher = self::CAUGHT_BY_OTHER
190 ) {
191 self::rollbackPrimaryChanges();
192
193 self::logException( $e, $catcher );
194 }
195
201 public static function rollbackMasterChangesAndLog(
202 Throwable $e,
203 $catcher = self::CAUGHT_BY_OTHER
204 ) {
205 wfDeprecated( __METHOD__, '1.37' );
206 self::rollbackPrimaryChangesAndLog( $e, $catcher );
207 }
208
215 public static function handleUncaughtException( Throwable $e ) {
216 self::handleException( $e, self::CAUGHT_BY_HANDLER );
217
218 // Make sure we don't claim success on exit for CLI scripts (T177414)
219 if ( wfIsCLI() ) {
220 register_shutdown_function(
224 static function () {
225 exit( 255 );
226 }
227 );
228 }
229 }
230
246 public static function handleException( Throwable $e, $catcher = self::CAUGHT_BY_OTHER ) {
247 self::rollbackPrimaryChangesAndLog( $e, $catcher );
248 self::report( $e );
249 }
250
265 public static function handleError(
266 $level,
267 $message,
268 $file = null,
269 $line = null
270 ) {
271 // Map PHP error constant to a PSR-3 severity level.
272 // Avoid use of "DEBUG" or "INFO" levels, unless the
273 // error should evade error monitoring and alerts.
274 //
275 // To decide the log level, ask yourself: "Has the
276 // program's behaviour diverged from what the written
277 // code expected?"
278 //
279 // For example, use of a deprecated method or violating a strict standard
280 // has no impact on functional behaviour (Warning). On the other hand,
281 // accessing an undefined variable makes behaviour diverge from what the
282 // author intended/expected. PHP recovers from an undefined variables by
283 // yielding null and continuing execution, but it remains a change in
284 // behaviour given the null was not part of the code and is likely not
285 // accounted for.
286 switch ( $level ) {
287 case E_WARNING:
288 case E_CORE_WARNING:
289 case E_COMPILE_WARNING:
290 $prefix = 'PHP Warning: ';
291 $severity = LogLevel::ERROR;
292 break;
293 case E_NOTICE:
294 $prefix = 'PHP Notice: ';
295 $severity = LogLevel::ERROR;
296 break;
297 case E_USER_NOTICE:
298 // Used by wfWarn(), MWDebug::warning()
299 $prefix = 'PHP Notice: ';
300 $severity = LogLevel::WARNING;
301 break;
302 case E_USER_WARNING:
303 // Used by wfWarn(), MWDebug::warning()
304 $prefix = 'PHP Warning: ';
305 $severity = LogLevel::WARNING;
306 break;
307 case E_STRICT:
308 $prefix = 'PHP Strict Standards: ';
309 $severity = LogLevel::WARNING;
310 break;
311 case E_DEPRECATED:
312 $prefix = 'PHP Deprecated: ';
313 $severity = LogLevel::WARNING;
314 break;
315 case E_USER_DEPRECATED:
316 $prefix = 'PHP Deprecated: ';
317 $severity = LogLevel::WARNING;
318 $real = MWDebug::parseCallerDescription( $message );
319 if ( $real ) {
320 // Used by wfDeprecated(), MWDebug::deprecated()
321 // Apply caller offset from wfDeprecated() to the native error.
322 // This makes errors easier to aggregate and find in e.g. Kibana.
323 $file = $real['file'];
324 $line = $real['line'];
325 $message = $real['message'];
326 }
327 break;
328 default:
329 $prefix = 'PHP Unknown error: ';
330 $severity = LogLevel::ERROR;
331 break;
332 }
333
334 // @phan-suppress-next-line PhanTypeMismatchArgumentNullableInternal False positive
335 $e = new ErrorException( $prefix . $message, 0, $level, $file, $line );
336 self::logError( $e, 'error', $severity, self::CAUGHT_BY_HANDLER );
337
338 // If $propagateErrors is true return false so PHP shows/logs the error normally.
339 // Ignore $propagateErrors if track_errors is set
340 // (which means someone is counting on regular PHP error handling behavior).
341 return !( self::$propagateErrors || ini_get( 'track_errors' ) );
342 }
343
358 public static function handleFatalError() {
359 // Free reserved memory so that we have space to process OOM
360 // errors
361 self::$reservedMemory = null;
362
363 $lastError = error_get_last();
364 if ( $lastError === null ) {
365 return false;
366 }
367
368 $level = $lastError['type'];
369 $message = $lastError['message'];
370 $file = $lastError['file'];
371 $line = $lastError['line'];
372
373 if ( !in_array( $level, self::$fatalErrorTypes ) ) {
374 // Only interested in fatal errors, others should have been
375 // handled by MWExceptionHandler::handleError
376 return false;
377 }
378
379 $msgParts = [
380 '[{reqId}] {exception_url} PHP Fatal Error',
381 ( $line || $file ) ? ' from' : '',
382 $line ? " line $line" : '',
383 ( $line && $file ) ? ' of' : '',
384 $file ? " $file" : '',
385 ": $message",
386 ];
387 $msg = implode( '', $msgParts );
388
389 // Look at message to see if this is a class not found failure (Class 'foo' not found)
390 if ( preg_match( "/Class '\w+' not found/", $message ) ) {
391 // phpcs:disable Generic.Files.LineLength
392 $msg = <<<TXT
393{$msg}
394
395MediaWiki 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.
396
397Please see <a href="https://www.mediawiki.org/wiki/Download_from_Git#Fetch_external_libraries">mediawiki.org</a> for help on installing the required components.
398TXT;
399 // phpcs:enable
400 }
401
402 $e = new ErrorException( "PHP Fatal Error: {$message}", 0, $level, $file, $line );
403 $logger = LoggerFactory::getInstance( 'exception' );
404 $logger->error( $msg, self::getLogContext( $e, self::CAUGHT_BY_HANDLER ) );
405
406 return false;
407 }
408
419 public static function getRedactedTraceAsString( Throwable $e ) {
420 $from = 'from ' . $e->getFile() . '(' . $e->getLine() . ')' . "\n";
421 return $from . self::prettyPrintTrace( self::getRedactedTrace( $e ) );
422 }
423
432 public static function prettyPrintTrace( array $trace, $pad = '' ) {
433 $text = '';
434
435 $level = 0;
436 foreach ( $trace as $level => $frame ) {
437 if ( isset( $frame['file'] ) && isset( $frame['line'] ) ) {
438 $text .= "{$pad}#{$level} {$frame['file']}({$frame['line']}): ";
439 } else {
440 // 'file' and 'line' are unset for calls from C code
441 // (T57634) This matches behaviour of
442 // Throwable::getTraceAsString to instead display "[internal
443 // function]".
444 $text .= "{$pad}#{$level} [internal function]: ";
445 }
446
447 if ( isset( $frame['class'] ) && isset( $frame['type'] ) && isset( $frame['function'] ) ) {
448 $text .= $frame['class'] . $frame['type'] . $frame['function'];
449 } else {
450 $text .= $frame['function'] ?? 'NO_FUNCTION_GIVEN';
451 }
452
453 if ( isset( $frame['args'] ) ) {
454 $text .= '(' . implode( ', ', $frame['args'] ) . ")\n";
455 } else {
456 $text .= "()\n";
457 }
458 }
459
460 $level++;
461 $text .= "{$pad}#{$level} {main}";
462
463 return $text;
464 }
465
477 public static function getRedactedTrace( Throwable $e ) {
478 return static::redactTrace( $e->getTrace() );
479 }
480
491 public static function redactTrace( array $trace ) {
492 return array_map( static function ( $frame ) {
493 if ( isset( $frame['args'] ) ) {
494 $frame['args'] = array_map( static function ( $arg ) {
495 return is_object( $arg ) ? get_class( $arg ) : gettype( $arg );
496 }, $frame['args'] );
497 }
498 return $frame;
499 }, $trace );
500 }
501
509 public static function getURL() {
510 global $wgRequest;
511 if ( !isset( $wgRequest ) || $wgRequest instanceof FauxRequest ) {
512 return false;
513 }
514 return $wgRequest->getRequestURL();
515 }
516
528 public static function getLogMessage( Throwable $e ) {
529 $id = WebRequest::getRequestId();
530 $type = get_class( $e );
531 $message = $e->getMessage();
532 $url = self::getURL() ?: '[no req]';
533
534 if ( $e instanceof DBQueryError ) {
535 $message = "A database query error has occurred. Did you forget to run"
536 . " your application's database schema updater after upgrading"
537 . " or after adding a new extension?\n\nPlease see"
538 . " https://www.mediawiki.org/wiki/Special:MyLanguage/Manual:Upgrading and"
539 . " https://www.mediawiki.org/wiki/Special:MyLanguage/Manual:How_to_debug"
540 . " for more information.\n\n"
541 . $message;
542 }
543
544 return "[$id] $url $type: $message";
545 }
546
556 public static function getLogNormalMessage( Throwable $e ) {
557 if ( $e instanceof INormalizedException ) {
558 $message = $e->getNormalizedMessage();
559 } else {
560 $message = $e->getMessage();
561 }
562 if ( !$e instanceof ErrorException ) {
563 // ErrorException is something we use internally to represent
564 // PHP errors (runtime warnings that aren't thrown or caught),
565 // don't bother putting it in the logs. Let the log message
566 // lead with "PHP Warning: " instead (see ::handleError).
567 $message = get_class( $e ) . ": $message";
568 }
569
570 return "[{reqId}] {exception_url} $message";
571 }
572
577 public static function getPublicLogMessage( Throwable $e ) {
578 $reqId = WebRequest::getRequestId();
579 $type = get_class( $e );
580 return '[' . $reqId . '] '
581 . gmdate( 'Y-m-d H:i:s' ) . ': '
582 . 'Fatal exception of type "' . $type . '"';
583 }
584
597 public static function getLogContext( Throwable $e, $catcher = self::CAUGHT_BY_OTHER ) {
598 $context = [
599 'exception' => $e,
600 'exception_url' => self::getURL() ?: '[no req]',
601 // The reqId context key use the same familiar name and value as the top-level field
602 // provided by LogstashFormatter. However, formatters are configurable at run-time,
603 // and their top-level fields are logically separate from context keys and cannot be,
604 // substituted in a message, hence set explicitly here. For WMF users, these may feel,
605 // like the same thing due to Monolog V0 handling, which transmits "fields" and "context",
606 // in the same JSON object (after message formatting).
607 'reqId' => WebRequest::getRequestId(),
608 'caught_by' => $catcher
609 ];
610 if ( $e instanceof INormalizedException ) {
611 $context += $e->getMessageContext();
612 }
613 return $context;
614 }
615
628 public static function getStructuredExceptionData(
629 Throwable $e,
630 $catcher = self::CAUGHT_BY_OTHER
631 ) {
632 $data = [
633 'id' => WebRequest::getRequestId(),
634 'type' => get_class( $e ),
635 'file' => $e->getFile(),
636 'line' => $e->getLine(),
637 'message' => $e->getMessage(),
638 'code' => $e->getCode(),
639 'url' => self::getURL() ?: null,
640 'caught_by' => $catcher
641 ];
642
643 if ( $e instanceof ErrorException &&
644 ( error_reporting() & $e->getSeverity() ) === 0
645 ) {
646 // Flag suppressed errors
647 $data['suppressed'] = true;
648 }
649
650 if ( self::$logExceptionBacktrace ) {
651 $data['backtrace'] = self::getRedactedTrace( $e );
652 }
653
654 $previous = $e->getPrevious();
655 if ( $previous !== null ) {
656 $data['previous'] = self::getStructuredExceptionData( $previous, $catcher );
657 }
658
659 return $data;
660 }
661
716 public static function jsonSerializeException(
717 Throwable $e,
718 $pretty = false,
719 $escaping = 0,
720 $catcher = self::CAUGHT_BY_OTHER
721 ) {
722 return FormatJson::encode(
723 self::getStructuredExceptionData( $e, $catcher ),
724 $pretty,
725 $escaping
726 );
727 }
728
740 public static function logException(
741 Throwable $e,
742 $catcher = self::CAUGHT_BY_OTHER,
743 $extraData = []
744 ) {
745 if ( !( $e instanceof MWException ) || $e->isLoggable() ) {
746 $logger = LoggerFactory::getInstance( 'exception' );
747 $context = self::getLogContext( $e, $catcher );
748 if ( $extraData ) {
749 $context['extraData'] = $extraData;
750 }
751 $logger->error(
752 self::getLogNormalMessage( $e ),
753 $context
754 );
755
756 $json = self::jsonSerializeException( $e, false, FormatJson::ALL_OK, $catcher );
757 if ( $json !== false ) {
758 $logger = LoggerFactory::getInstance( 'exception-json' );
759 $logger->error( $json, [ 'private' => true ] );
760 }
761
762 Hooks::runner()->onLogException( $e, false );
763 }
764 }
765
774 private static function logError(
775 ErrorException $e,
776 $channel,
777 $level,
778 $catcher
779 ) {
780 // The set_error_handler callback is independent from error_reporting.
781 // Filter out unwanted errors manually (e.g. when
782 // AtEase::suppressWarnings is active).
783 $suppressed = ( error_reporting() & $e->getSeverity() ) === 0;
784 if ( !$suppressed ) {
785 $logger = LoggerFactory::getInstance( $channel );
786 $logger->log(
787 $level,
788 self::getLogNormalMessage( $e ),
789 self::getLogContext( $e, $catcher )
790 );
791 }
792
793 // Include all errors in the json log (suppressed errors will be flagged)
794 $json = self::jsonSerializeException( $e, false, FormatJson::ALL_OK, $catcher );
795 if ( $json !== false ) {
796 $logger = LoggerFactory::getInstance( "{$channel}-json" );
797 // Unlike the 'error' channel, the 'error-json' channel is unfiltered,
798 // and emits messages even if wikimedia/at-ease was used to suppress the
799 // error. To avoid clobbering Logstash dashboards with these, make sure
800 // those have their level casted to DEBUG so that they are excluded by
801 // level-based filters automatically instead of requiring a dedicated filter
802 // for this channel. To be improved: T193472.
803 $unfilteredLevel = $suppressed ? LogLevel::DEBUG : $level;
804 $logger->log( $unfilteredLevel, $json, [ 'private' => true ] );
805 }
806
807 Hooks::runner()->onLogException( $e, $suppressed );
808 }
809}
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that a deprecated feature was used.
wfIsCLI()
Check if we are running from the commandline.
global $wgRequest
Definition Setup.php:377
WebRequest clone which takes values from a provided array.
static runner()
Get a HookRunner instance for calling hooks using the new interfaces.
Definition Hooks.php:173
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 rollbackMasterChangesAndLog(Throwable $e, $catcher=self::CAUGHT_BY_OTHER)
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.
PSR-3 logger instance factory.
Service locator for MediaWiki core services.
Database error base class.
Definition DBError.php:31
$line
Definition mcc.php:119
A helper class for throttling authentication attempts.
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition router.php:42