3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
21 use MediaWiki\Debug\MWDebug
;
22 use MediaWiki\HookContainer\HookRunner
;
23 use MediaWiki\Json\FormatJson
;
24 use MediaWiki\Logger\LoggerFactory
;
25 use MediaWiki\MediaWikiServices
;
26 use MediaWiki\Request\WebRequest
;
28 use Wikimedia\NormalizedException\INormalizedException
;
29 use Wikimedia\Rdbms\DBError
;
30 use Wikimedia\Rdbms\DBQueryError
;
31 use Wikimedia\Rdbms\LBFactory
;
32 use Wikimedia\Services\RecursiveServiceDependencyException
;
35 * Handler class for MWExceptions
38 class MWExceptionHandler
{
39 /** Error caught and reported by this exception handler */
40 public const CAUGHT_BY_HANDLER
= 'mwe_handler';
41 /** Error caught and reported by a script entry point */
42 public const CAUGHT_BY_ENTRYPOINT
= 'entrypoint';
43 /** Error reported by direct logException() call */
44 public const CAUGHT_BY_OTHER
= 'other';
46 /** @var string|null */
47 protected static $reservedMemory;
50 * Error types that, if unhandled, are fatal to the request.
51 * These error types may be thrown as Error objects, which implement Throwable (but not Exception).
53 * The user will be shown an HTTP 500 Internal Server Error.
54 * As such, these should be sent to MediaWiki's "exception" channel.
55 * Normally, the error handler logs them to the "error" channel.
57 private const FATAL_ERROR_TYPES
= [
64 // E.g. "Catchable fatal error: Argument X must be Y, null given"
69 * Whether exception data should include a backtrace.
73 private static $logExceptionBacktrace = true;
76 * Whether to propagate errors to PHP's built-in handler.
80 private static $propagateErrors;
83 * Install handlers with PHP.
85 * @param bool $logExceptionBacktrace Whether error handlers should include a backtrace
87 * @param bool $propagateErrors Whether errors should be propagated to PHP's built-in handler.
89 public static function installHandler(
90 bool $logExceptionBacktrace = true,
91 bool $propagateErrors = true
93 self
::$logExceptionBacktrace = $logExceptionBacktrace;
94 self
::$propagateErrors = $propagateErrors;
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' ] );
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' ] );
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' ] );
123 * Report a throwable to the user
125 protected static function report( Throwable
$e ) {
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
134 MWExceptionRenderer
::output( $e, MWExceptionRenderer
::AS_PRETTY
);
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 );
145 * Roll back any open database transactions
147 * This method is used to attempt to recover from exceptions
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.
156 $services = MediaWikiServices
::getInstance();
157 $lbFactory = $services->peekService( 'DBLoadBalancerFactory' );
158 '@phan-var LBFactory $lbFactory'; /* @var LBFactory $lbFactory */
160 // There's no need to roll back transactions if the LBFactory is
161 // disabled or hasn't been created yet
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.
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
);
182 * Roll back any open database transactions and log the stack trace of the throwable
184 * This method is used to attempt to recover from exceptions
187 * @param Throwable $e
188 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
190 public static function rollbackPrimaryChangesAndLog(
192 $catcher = self
::CAUGHT_BY_OTHER
194 self
::rollbackPrimaryChanges();
196 self
::logException( $e, $catcher );
200 * Callback to use with PHP's set_exception_handler.
203 * @param Throwable $e
205 public static function handleUncaughtException( Throwable
$e ) {
206 self
::handleException( $e, self
::CAUGHT_BY_HANDLER
);
208 // Make sure we don't claim success on exit for CLI scripts (T177414)
210 register_shutdown_function(
222 * Exception handler which simulates the appropriate catch() handling:
226 * } catch ( Exception $e ) {
228 * } catch ( Exception $e ) {
229 * echo $e->__toString();
233 * @param Throwable $e
234 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
236 public static function handleException( Throwable
$e, $catcher = self
::CAUGHT_BY_OTHER
) {
237 self
::rollbackPrimaryChangesAndLog( $e, $catcher );
242 * Handler for set_error_handler() callback notifications.
244 * Receive a callback from the interpreter for a raised error, create an
245 * ErrorException, and log the exception to the 'error' logging
249 * @param int $level Error level raised
250 * @param string $message
251 * @param string|null $file
252 * @param int|null $line
255 public static function handleError(
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
;
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.
271 // To decide the log level, ask yourself: "Has the
272 // program's behaviour diverged from what the written
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
285 case E_COMPILE_WARNING
:
286 $prefix = 'PHP Warning: ';
287 $severity = LogLevel
::ERROR
;
290 $prefix = 'PHP Notice: ';
291 $severity = LogLevel
::ERROR
;
294 // Used by wfWarn(), MWDebug::warning()
295 $prefix = 'PHP Notice: ';
296 $severity = LogLevel
::WARNING
;
299 // Used by wfWarn(), MWDebug::warning()
300 $prefix = 'PHP Warning: ';
301 $severity = LogLevel
::WARNING
;
304 $prefix = 'PHP Deprecated: ';
305 $severity = LogLevel
::WARNING
;
307 case E_USER_DEPRECATED
:
308 $prefix = 'PHP Deprecated: ';
309 $severity = LogLevel
::WARNING
;
310 $real = MWDebug
::parseCallerDescription( $message );
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'];
321 $prefix = 'PHP Unknown error: ';
322 $severity = LogLevel
::ERROR
;
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
);
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' ) );
337 * Callback used as a registered shutdown function.
339 * This is used as callback from the interpreter at system shutdown.
340 * If the last error was not a recoverable error that we already reported,
341 * and log as fatal exception.
343 * Special handling is included for missing class errors as they may
344 * indicate that the user needs to install 3rd-party libraries via
345 * Composer or other means.
348 * @return bool Always returns false
350 public static function handleFatalError() {
351 // Free reserved memory so that we have space to process OOM
353 self
::$reservedMemory = null;
355 $lastError = error_get_last();
356 if ( $lastError === null ) {
360 $level = $lastError['type'];
361 $message = $lastError['message'];
362 $file = $lastError['file'];
363 $line = $lastError['line'];
365 if ( !in_array( $level, self
::FATAL_ERROR_TYPES
) ) {
366 // Only interested in fatal errors, others should have been
367 // handled by MWExceptionHandler::handleError
372 '[{reqId}] {exception_url} PHP Fatal Error',
373 ( $line ||
$file ) ?
' from' : '',
374 $line ?
" line $line" : '',
375 ( $line && $file ) ?
' of' : '',
376 $file ?
" $file" : '',
379 $msg = implode( '', $msgParts );
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
387 MediaWiki 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.
389 Please see <a href="https://www.mediawiki.org/wiki/Download_from_Git#Fetch_external_libraries">mediawiki.org</a> for help on installing the required components.
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
) );
402 * Generate a string representation of a throwable's stack trace
404 * Like Throwable::getTraceAsString, but replaces argument values with
405 * their type or class name, and prepends the start line of the throwable.
407 * @param Throwable $e
409 * @see prettyPrintTrace()
411 public static function getRedactedTraceAsString( Throwable
$e ) {
412 $from = 'from ' . $e->getFile() . '(' . $e->getLine() . ')' . "\n";
413 return $from . self
::prettyPrintTrace( self
::getRedactedTrace( $e ) );
417 * Generate a string representation of a stacktrace.
420 * @param array $trace
421 * @param string $pad Constant padding to add to each line of trace
424 public static function prettyPrintTrace( array $trace, $pad = '' ) {
428 foreach ( $trace as $level => $frame ) {
429 if ( isset( $frame['file'] ) && isset( $frame['line'] ) ) {
430 $text .= "{$pad}#{$level} {$frame['file']}({$frame['line']}): ";
432 // 'file' and 'line' are unset for calls from C code
433 // (T57634) This matches behaviour of
434 // Throwable::getTraceAsString to instead display "[internal
436 $text .= "{$pad}#{$level} [internal function]: ";
439 if ( isset( $frame['class'] ) && isset( $frame['type'] ) && isset( $frame['function'] ) ) {
440 $text .= $frame['class'] . $frame['type'] . $frame['function'];
442 $text .= $frame['function'] ??
'NO_FUNCTION_GIVEN';
445 if ( isset( $frame['args'] ) ) {
446 $text .= '(' . implode( ', ', $frame['args'] ) . ")\n";
453 $text .= "{$pad}#{$level} {main}";
459 * Return a copy of a throwable's backtrace as an array.
461 * Like Throwable::getTrace, but replaces each element in each frame's
462 * argument array with the name of its class (if the element is an object)
463 * or its type (if the element is a PHP primitive).
466 * @param Throwable $e
469 public static function getRedactedTrace( Throwable
$e ) {
470 return static::redactTrace( $e->getTrace() );
474 * Redact a stacktrace generated by Throwable::getTrace(),
475 * debug_backtrace() or similar means. Replaces each element in each
476 * frame's argument array with the name of its class (if the element is an
477 * object) or its type (if the element is a PHP primitive).
480 * @param array $trace Stacktrace
481 * @return array Stacktrace with argument values converted to data types
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'] );
493 * If the exception occurred in the course of responding to a request,
494 * returns the requested URL. Otherwise, returns false.
497 * @return string|false
499 public static function getURL() {
500 if ( MW_ENTRY_POINT
=== 'cli' ) {
503 return WebRequest
::getGlobalRequestURL();
507 * Get a message formatting the throwable message and its origin.
509 * Despite the method name, this is not used for logging.
510 * It is only used for HTML or CLI output by MWExceptionRenderer.
513 * @param Throwable $e
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]';
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"
532 return "[$id] $url $type: $message";
536 * Get a normalised message for formatting with PSR-3 log event context.
538 * Must be used together with `getLogContext()` to be useful.
541 * @param Throwable $e
544 public static function getLogNormalMessage( Throwable
$e ) {
545 if ( $e instanceof INormalizedException
) {
546 $message = $e->getNormalizedMessage();
548 $message = $e->getMessage();
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";
558 return "[{reqId}] {exception_url} $message";
562 * @param Throwable $e
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 . '"';
574 * Get a PSR-3 log event context from a Throwable.
576 * Creates a structured array containing information about the provided
577 * throwable that can be used to augment a log message sent to a PSR-3
581 * @param Throwable $e
582 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
585 public static function getLogContext( Throwable
$e, $catcher = self
::CAUGHT_BY_OTHER
) {
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
598 if ( $e instanceof INormalizedException
) {
599 $context +
= $e->getMessageContext();
605 * Get a structured representation of a Throwable.
607 * Returns an array of structured data (class, message, code, file,
608 * backtrace) derived from the given throwable. The backtrace information
609 * will be redacted as per getRedactedTraceAsArray().
611 * @param Throwable $e
612 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
616 public static function getStructuredExceptionData(
618 $catcher = self
::CAUGHT_BY_OTHER
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
631 if ( $e instanceof ErrorException
&&
632 ( error_reporting() & $e->getSeverity() ) === 0
634 // Flag suppressed errors
635 $data['suppressed'] = true;
638 if ( self
::$logExceptionBacktrace ) {
639 $data['backtrace'] = self
::getRedactedTrace( $e );
642 $previous = $e->getPrevious();
643 if ( $previous !== null ) {
644 $data['previous'] = self
::getStructuredExceptionData( $previous, $catcher );
651 * Serialize a Throwable object to JSON.
653 * The JSON object will have keys 'id', 'file', 'line', 'message', and
654 * 'url'. These keys map to string values, with the exception of 'line',
655 * which is a number, and 'url', which may be either a string URL or
656 * null if the throwable did not occur in the context of serving a web
659 * If $wgLogExceptionBacktrace is true, it will also have a 'backtrace'
660 * key, mapped to the array return value of Throwable::getTrace, but with
661 * each element in each frame's "args" array (if set) replaced with the
662 * argument's class name (if the argument is an object) or type name (if
663 * the argument is a PHP primitive).
665 * @par Sample JSON record ($wgLogExceptionBacktrace = false):
669 * "type": "Exception",
670 * "file": "/var/www/mediawiki/includes/cache/MessageCache.php",
672 * "message": "Example message",
673 * "url": "/wiki/Main_Page"
677 * @par Sample JSON record ($wgLogExceptionBacktrace = true):
681 * "type": "Exception",
682 * "file": "/var/www/mediawiki/includes/cache/MessageCache.php",
684 * "message": "Example message",
685 * "url": "/wiki/Main_Page",
687 * "file": "/var/www/mediawiki/includes/OutputPage.php",
690 * "class": "MessageCache",
698 * @param Throwable $e
699 * @param bool $pretty Add non-significant whitespace to improve readability (default: false).
700 * @param int $escaping Bitfield consisting of FormatJson::.*_OK class constants.
701 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
702 * @return string|false JSON string if successful; false upon failure
704 public static function jsonSerializeException(
708 $catcher = self
::CAUGHT_BY_OTHER
710 return FormatJson
::encode(
711 self
::getStructuredExceptionData( $e, $catcher ),
718 * Log a throwable to the exception log (if enabled).
720 * This method must not assume the throwable is an MWException,
721 * it is also used to handle PHP exceptions or exceptions from other libraries.
724 * @param Throwable $e
725 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
726 * @param array $extraData (since 1.34) Additional data to log
728 public static function logException(
730 $catcher = self
::CAUGHT_BY_OTHER
,
733 if ( !( $e instanceof MWException
) ||
$e->isLoggable() ) {
734 $logger = LoggerFactory
::getInstance( 'exception' );
735 $context = self
::getLogContext( $e, $catcher );
737 $context['extraData'] = $extraData;
740 self
::getLogNormalMessage( $e ),
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 ] );
750 self
::callLogExceptionHook( $e, false );
755 * Log an exception that wasn't thrown but made to wrap an error.
757 * @param ErrorException $e
758 * @param string $level
759 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
761 private static function logError(
766 // The set_error_handler callback is independent from error_reporting.
767 $suppressed = ( error_reporting() & $e->getSeverity() ) === 0;
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
;
779 $logger = LoggerFactory
::getInstance( $channel );
782 self
::getLogNormalMessage( $e ),
783 self
::getLogContext( $e, $catcher )
786 self
::callLogExceptionHook( $e, $suppressed );
790 * Call the LogException hook, suppressing some exceptions.
792 * @param Throwable $e
793 * @param bool $suppressed
795 private static function callLogExceptionHook( Throwable
$e, bool $suppressed ) {
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() ) {
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)