MediaWiki master
MWExceptionHandler.php
Go to the documentation of this file.
1<?php
26use Psr\Log\LogLevel;
27use Wikimedia\NormalizedException\INormalizedException;
30
37 public const CAUGHT_BY_HANDLER = 'mwe_handler';
39 public const CAUGHT_BY_ENTRYPOINT = 'entrypoint';
41 public const CAUGHT_BY_OTHER = 'other';
42
44 protected static $reservedMemory;
45
56 protected static $fatalErrorTypes = [
57 E_ERROR,
58 E_PARSE,
59 E_CORE_ERROR,
60 E_COMPILE_ERROR,
61 E_USER_ERROR,
62
63 // E.g. "Catchable fatal error: Argument X must be Y, null given"
64 E_RECOVERABLE_ERROR,
65 ];
66
72 private static $logExceptionBacktrace = true;
73
79 private static $propagateErrors;
80
88 public static function installHandler(
89 bool $logExceptionBacktrace = true,
90 bool $propagateErrors = true
91 ) {
92 self::$logExceptionBacktrace = $logExceptionBacktrace;
93 self::$propagateErrors = $propagateErrors;
94
95 // This catches:
96 // * Exception objects that were explicitly thrown but not
97 // caught anywhere in the application. This is rare given those
98 // would normally be caught at a high-level like MediaWiki::run (index.php),
99 // api.php, or ResourceLoader::respond (load.php). These high-level
100 // catch clauses would then call MWExceptionHandler::logException
101 // or MWExceptionHandler::handleException.
102 // If they are not caught, then they are handled here.
103 // * Error objects for issues that would historically
104 // cause fatal errors but may now be caught as Throwable (not Exception).
105 // Same as previous case, but more common to bubble to here instead of
106 // caught locally because they tend to not be safe to recover from.
107 // (e.g. argument TypeError, division by zero, etc.)
108 set_exception_handler( [ self::class, 'handleUncaughtException' ] );
109
110 // This catches recoverable errors (e.g. PHP Notice, PHP Warning, PHP Error) that do not
111 // interrupt execution in any way. We log these in the background and then continue execution.
112 set_error_handler( [ self::class, 'handleError' ] );
113
114 // This catches fatal errors for which no Throwable is thrown,
115 // including Out-Of-Memory and Timeout fatals.
116 // Reserve 16k of memory so we can report OOM fatals.
117 self::$reservedMemory = str_repeat( ' ', 16384 );
118 register_shutdown_function( [ self::class, 'handleFatalError' ] );
119 }
120
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 if ( $services->isServiceDisabled( 'DBLoadBalancerFactory' ) ) {
158 // The DBLoadBalancerFactory is disabled, possibly because we are in the installer,
159 // or we are in the process of shutting MediaWiki. At this point, any DB transactions
160 // would already have been committed or rolled back.
161 return;
162 }
163
164 // Roll back DBs to avoid transaction notices. This might fail
165 // to roll back some databases due to connection issues or exceptions.
166 // However, any sensible DB driver will roll back implicitly anyway.
167 try {
168 $lbFactory = $services->getDBLoadBalancerFactory();
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 // Map PHP error constant to a PSR-3 severity level.
262 // Avoid use of "DEBUG" or "INFO" levels, unless the
263 // error should evade error monitoring and alerts.
264 //
265 // To decide the log level, ask yourself: "Has the
266 // program's behaviour diverged from what the written
267 // code expected?"
268 //
269 // For example, use of a deprecated method or violating a strict standard
270 // has no impact on functional behaviour (Warning). On the other hand,
271 // accessing an undefined variable makes behaviour diverge from what the
272 // author intended/expected. PHP recovers from an undefined variables by
273 // yielding null and continuing execution, but it remains a change in
274 // behaviour given the null was not part of the code and is likely not
275 // accounted for.
276 switch ( $level ) {
277 case E_WARNING:
278 case E_CORE_WARNING:
279 case E_COMPILE_WARNING:
280 $prefix = 'PHP Warning: ';
281 $severity = LogLevel::ERROR;
282 break;
283 case E_NOTICE:
284 $prefix = 'PHP Notice: ';
285 $severity = LogLevel::ERROR;
286 break;
287 case E_USER_NOTICE:
288 // Used by wfWarn(), MWDebug::warning()
289 $prefix = 'PHP Notice: ';
290 $severity = LogLevel::WARNING;
291 break;
292 case E_USER_WARNING:
293 // Used by wfWarn(), MWDebug::warning()
294 $prefix = 'PHP Warning: ';
295 $severity = LogLevel::WARNING;
296 break;
297 case E_STRICT:
298 $prefix = 'PHP Strict Standards: ';
299 $severity = LogLevel::WARNING;
300 break;
301 case E_DEPRECATED:
302 $prefix = 'PHP Deprecated: ';
303 $severity = LogLevel::WARNING;
304 break;
305 case E_USER_DEPRECATED:
306 $prefix = 'PHP Deprecated: ';
307 $severity = LogLevel::WARNING;
308 $real = MWDebug::parseCallerDescription( $message );
309 if ( $real ) {
310 // Used by wfDeprecated(), MWDebug::deprecated()
311 // Apply caller offset from wfDeprecated() to the native error.
312 // This makes errors easier to aggregate and find in e.g. Kibana.
313 $file = $real['file'];
314 $line = $real['line'];
315 $message = $real['message'];
316 }
317 break;
318 default:
319 $prefix = 'PHP Unknown error: ';
320 $severity = LogLevel::ERROR;
321 break;
322 }
323
324 // @phan-suppress-next-line PhanTypeMismatchArgumentNullableInternal False positive
325 $e = new ErrorException( $prefix . $message, 0, $level, $file, $line );
326 self::logError( $e, $severity, self::CAUGHT_BY_HANDLER );
327
328 // If $propagateErrors is true return false so PHP shows/logs the error normally.
329 // Ignore $propagateErrors if track_errors is set
330 // (which means someone is counting on regular PHP error handling behavior).
331 return !( self::$propagateErrors || ini_get( 'track_errors' ) );
332 }
333
348 public static function handleFatalError() {
349 // Free reserved memory so that we have space to process OOM
350 // errors
351 self::$reservedMemory = null;
352
353 $lastError = error_get_last();
354 if ( $lastError === null ) {
355 return false;
356 }
357
358 $level = $lastError['type'];
359 $message = $lastError['message'];
360 $file = $lastError['file'];
361 $line = $lastError['line'];
362
363 if ( !in_array( $level, self::$fatalErrorTypes ) ) {
364 // Only interested in fatal errors, others should have been
365 // handled by MWExceptionHandler::handleError
366 return false;
367 }
368
369 $msgParts = [
370 '[{reqId}] {exception_url} PHP Fatal Error',
371 ( $line || $file ) ? ' from' : '',
372 $line ? " line $line" : '',
373 ( $line && $file ) ? ' of' : '',
374 $file ? " $file" : '',
375 ": $message",
376 ];
377 $msg = implode( '', $msgParts );
378
379 // Look at message to see if this is a class not found failure (Class 'foo' not found)
380 if ( preg_match( "/Class '\w+' not found/", $message ) ) {
381 // phpcs:disable Generic.Files.LineLength
382 $msg = <<<TXT
383{$msg}
384
385MediaWiki 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.
386
387Please see <a href="https://www.mediawiki.org/wiki/Download_from_Git#Fetch_external_libraries">mediawiki.org</a> for help on installing the required components.
388TXT;
389 // phpcs:enable
390 }
391
392 $e = new ErrorException( "PHP Fatal Error: {$message}", 0, $level, $file, $line );
393 $logger = LoggerFactory::getInstance( 'exception' );
394 $logger->error( $msg, self::getLogContext( $e, self::CAUGHT_BY_HANDLER ) );
395
396 return false;
397 }
398
409 public static function getRedactedTraceAsString( Throwable $e ) {
410 $from = 'from ' . $e->getFile() . '(' . $e->getLine() . ')' . "\n";
411 return $from . self::prettyPrintTrace( self::getRedactedTrace( $e ) );
412 }
413
422 public static function prettyPrintTrace( array $trace, $pad = '' ) {
423 $text = '';
424
425 $level = 0;
426 foreach ( $trace as $level => $frame ) {
427 if ( isset( $frame['file'] ) && isset( $frame['line'] ) ) {
428 $text .= "{$pad}#{$level} {$frame['file']}({$frame['line']}): ";
429 } else {
430 // 'file' and 'line' are unset for calls from C code
431 // (T57634) This matches behaviour of
432 // Throwable::getTraceAsString to instead display "[internal
433 // function]".
434 $text .= "{$pad}#{$level} [internal function]: ";
435 }
436
437 if ( isset( $frame['class'] ) && isset( $frame['type'] ) && isset( $frame['function'] ) ) {
438 $text .= $frame['class'] . $frame['type'] . $frame['function'];
439 } else {
440 $text .= $frame['function'] ?? 'NO_FUNCTION_GIVEN';
441 }
442
443 if ( isset( $frame['args'] ) ) {
444 $text .= '(' . implode( ', ', $frame['args'] ) . ")\n";
445 } else {
446 $text .= "()\n";
447 }
448 }
449
450 $level++;
451 $text .= "{$pad}#{$level} {main}";
452
453 return $text;
454 }
455
467 public static function getRedactedTrace( Throwable $e ) {
468 return static::redactTrace( $e->getTrace() );
469 }
470
481 public static function redactTrace( array $trace ) {
482 return array_map( static function ( $frame ) {
483 if ( isset( $frame['args'] ) ) {
484 $frame['args'] = array_map( static function ( $arg ) {
485 return is_object( $arg ) ? get_class( $arg ) : gettype( $arg );
486 }, $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 ( 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.
Debug toolbar.
Definition MWDebug.php:48
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,...
Database error base class.
Definition DBError.php:36
A helper class for throttling authentication attempts.