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
124 * @param Throwable $e
126 protected static function report( Throwable
$e ) {
128 // Try and show the exception prettily, with the normal skin infrastructure
129 if ( $e instanceof MWException
&& $e->hasOverriddenHandler() ) {
130 // Delegate to MWException until all subclasses are handled by
131 // MWExceptionRenderer and MWException::report() has been
135 MWExceptionRenderer
::output( $e, MWExceptionRenderer
::AS_PRETTY
);
137 } catch ( Throwable
$e2 ) {
138 // Exception occurred from within exception handler
139 // Show a simpler message for the original exception,
140 // don't try to invoke report()
141 MWExceptionRenderer
::output( $e, MWExceptionRenderer
::AS_RAW
, $e2 );
146 * Roll back any open database transactions
148 * This method is used to attempt to recover from exceptions
150 private static function rollbackPrimaryChanges() {
151 if ( !MediaWikiServices
::hasInstance() ) {
152 // MediaWiki isn't fully initialized yet, it's not safe to access services.
153 // This also means that there's nothing to roll back yet.
157 $services = MediaWikiServices
::getInstance();
158 $lbFactory = $services->peekService( 'DBLoadBalancerFactory' );
159 '@phan-var LBFactory $lbFactory'; /* @var LBFactory $lbFactory */
161 // There's no need to roll back transactions if the LBFactory is
162 // disabled or hasn't been created yet
166 // Roll back DBs to avoid transaction notices. This might fail
167 // to roll back some databases due to connection issues or exceptions.
168 // However, any sensible DB driver will roll back implicitly anyway.
170 $lbFactory->rollbackPrimaryChanges( __METHOD__
);
171 $lbFactory->flushPrimarySessions( __METHOD__
);
172 } catch ( DBError
$e ) {
173 // If the DB is unreachable, rollback() will throw an error
174 // and the error report() method might need messages from the DB,
175 // which would result in an exception loop. PHP may escalate such
176 // errors to "Exception thrown without a stack frame" fatals, but
177 // it's better to be explicit here.
178 self
::logException( $e, self
::CAUGHT_BY_HANDLER
);
183 * Roll back any open database transactions and log the stack trace of the throwable
185 * This method is used to attempt to recover from exceptions
188 * @param Throwable $e
189 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
191 public static function rollbackPrimaryChangesAndLog(
193 $catcher = self
::CAUGHT_BY_OTHER
195 self
::rollbackPrimaryChanges();
197 self
::logException( $e, $catcher );
201 * Callback to use with PHP's set_exception_handler.
204 * @param Throwable $e
206 public static function handleUncaughtException( Throwable
$e ) {
207 self
::handleException( $e, self
::CAUGHT_BY_HANDLER
);
209 // Make sure we don't claim success on exit for CLI scripts (T177414)
211 register_shutdown_function(
223 * Exception handler which simulates the appropriate catch() handling:
227 * } catch ( Exception $e ) {
229 * } catch ( Exception $e ) {
230 * echo $e->__toString();
234 * @param Throwable $e
235 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
237 public static function handleException( Throwable
$e, $catcher = self
::CAUGHT_BY_OTHER
) {
238 self
::rollbackPrimaryChangesAndLog( $e, $catcher );
243 * Handler for set_error_handler() callback notifications.
245 * Receive a callback from the interpreter for a raised error, create an
246 * ErrorException, and log the exception to the 'error' logging
250 * @param int $level Error level raised
251 * @param string $message
252 * @param string|null $file
253 * @param int|null $line
256 public static function handleError(
262 // Map PHP error constant to a PSR-3 severity level.
263 // Avoid use of "DEBUG" or "INFO" levels, unless the
264 // error should evade error monitoring and alerts.
266 // To decide the log level, ask yourself: "Has the
267 // program's behaviour diverged from what the written
270 // For example, use of a deprecated method or violating a strict standard
271 // has no impact on functional behaviour (Warning). On the other hand,
272 // accessing an undefined variable makes behaviour diverge from what the
273 // author intended/expected. PHP recovers from an undefined variables by
274 // yielding null and continuing execution, but it remains a change in
275 // behaviour given the null was not part of the code and is likely not
280 case E_COMPILE_WARNING
:
281 $prefix = 'PHP Warning: ';
282 $severity = LogLevel
::ERROR
;
285 $prefix = 'PHP Notice: ';
286 $severity = LogLevel
::ERROR
;
289 // Used by wfWarn(), MWDebug::warning()
290 $prefix = 'PHP Notice: ';
291 $severity = LogLevel
::WARNING
;
294 // Used by wfWarn(), MWDebug::warning()
295 $prefix = 'PHP Warning: ';
296 $severity = LogLevel
::WARNING
;
299 $prefix = 'PHP Strict Standards: ';
300 $severity = LogLevel
::WARNING
;
303 $prefix = 'PHP Deprecated: ';
304 $severity = LogLevel
::WARNING
;
306 case E_USER_DEPRECATED
:
307 $prefix = 'PHP Deprecated: ';
308 $severity = LogLevel
::WARNING
;
309 $real = MWDebug
::parseCallerDescription( $message );
311 // Used by wfDeprecated(), MWDebug::deprecated()
312 // Apply caller offset from wfDeprecated() to the native error.
313 // This makes errors easier to aggregate and find in e.g. Kibana.
314 $file = $real['file'];
315 $line = $real['line'];
316 $message = $real['message'];
320 $prefix = 'PHP Unknown error: ';
321 $severity = LogLevel
::ERROR
;
325 // @phan-suppress-next-line PhanTypeMismatchArgumentNullableInternal False positive
326 $e = new ErrorException( $prefix . $message, 0, $level, $file, $line );
327 self
::logError( $e, $severity, self
::CAUGHT_BY_HANDLER
);
329 // If $propagateErrors is true return false so PHP shows/logs the error normally.
330 // Ignore $propagateErrors if track_errors is set
331 // (which means someone is counting on regular PHP error handling behavior).
332 return !( self
::$propagateErrors ||
ini_get( 'track_errors' ) );
336 * Callback used as a registered shutdown function.
338 * This is used as callback from the interpreter at system shutdown.
339 * If the last error was not a recoverable error that we already reported,
340 * and log as fatal exception.
342 * Special handling is included for missing class errors as they may
343 * indicate that the user needs to install 3rd-party libraries via
344 * Composer or other means.
347 * @return bool Always returns false
349 public static function handleFatalError() {
350 // Free reserved memory so that we have space to process OOM
352 self
::$reservedMemory = null;
354 $lastError = error_get_last();
355 if ( $lastError === null ) {
359 $level = $lastError['type'];
360 $message = $lastError['message'];
361 $file = $lastError['file'];
362 $line = $lastError['line'];
364 if ( !in_array( $level, self
::FATAL_ERROR_TYPES
) ) {
365 // Only interested in fatal errors, others should have been
366 // handled by MWExceptionHandler::handleError
371 '[{reqId}] {exception_url} PHP Fatal Error',
372 ( $line ||
$file ) ?
' from' : '',
373 $line ?
" line $line" : '',
374 ( $line && $file ) ?
' of' : '',
375 $file ?
" $file" : '',
378 $msg = implode( '', $msgParts );
380 // Look at message to see if this is a class not found failure (Class 'foo' not found)
381 if ( preg_match( "/Class '\w+' not found/", $message ) ) {
382 // phpcs:disable Generic.Files.LineLength
386 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.
388 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.
393 $e = new ErrorException( "PHP Fatal Error: {$message}", 0, $level, $file, $line );
394 $logger = LoggerFactory
::getInstance( 'exception' );
395 $logger->error( $msg, self
::getLogContext( $e, self
::CAUGHT_BY_HANDLER
) );
401 * Generate a string representation of a throwable's stack trace
403 * Like Throwable::getTraceAsString, but replaces argument values with
404 * their type or class name, and prepends the start line of the throwable.
406 * @param Throwable $e
408 * @see prettyPrintTrace()
410 public static function getRedactedTraceAsString( Throwable
$e ) {
411 $from = 'from ' . $e->getFile() . '(' . $e->getLine() . ')' . "\n";
412 return $from . self
::prettyPrintTrace( self
::getRedactedTrace( $e ) );
416 * Generate a string representation of a stacktrace.
419 * @param array $trace
420 * @param string $pad Constant padding to add to each line of trace
423 public static function prettyPrintTrace( array $trace, $pad = '' ) {
427 foreach ( $trace as $level => $frame ) {
428 if ( isset( $frame['file'] ) && isset( $frame['line'] ) ) {
429 $text .= "{$pad}#{$level} {$frame['file']}({$frame['line']}): ";
431 // 'file' and 'line' are unset for calls from C code
432 // (T57634) This matches behaviour of
433 // Throwable::getTraceAsString to instead display "[internal
435 $text .= "{$pad}#{$level} [internal function]: ";
438 if ( isset( $frame['class'] ) && isset( $frame['type'] ) && isset( $frame['function'] ) ) {
439 $text .= $frame['class'] . $frame['type'] . $frame['function'];
441 $text .= $frame['function'] ??
'NO_FUNCTION_GIVEN';
444 if ( isset( $frame['args'] ) ) {
445 $text .= '(' . implode( ', ', $frame['args'] ) . ")\n";
452 $text .= "{$pad}#{$level} {main}";
458 * Return a copy of a throwable's backtrace as an array.
460 * Like Throwable::getTrace, but replaces each element in each frame's
461 * argument array with the name of its class (if the element is an object)
462 * or its type (if the element is a PHP primitive).
465 * @param Throwable $e
468 public static function getRedactedTrace( Throwable
$e ) {
469 return static::redactTrace( $e->getTrace() );
473 * Redact a stacktrace generated by Throwable::getTrace(),
474 * debug_backtrace() or similar means. Replaces each element in each
475 * frame's argument array with the name of its class (if the element is an
476 * object) or its type (if the element is a PHP primitive).
479 * @param array $trace Stacktrace
480 * @return array Stacktrace with argument values converted to data types
482 public static function redactTrace( array $trace ) {
483 return array_map( static function ( $frame ) {
484 if ( isset( $frame['args'] ) ) {
485 $frame['args'] = array_map( 'get_debug_type', $frame['args'] );
492 * If the exception occurred in the course of responding to a request,
493 * returns the requested URL. Otherwise, returns false.
496 * @return string|false
498 public static function getURL() {
499 if ( MW_ENTRY_POINT
=== 'cli' ) {
502 return WebRequest
::getGlobalRequestURL();
506 * Get a message formatting the throwable message and its origin.
508 * Despite the method name, this is not used for logging.
509 * It is only used for HTML or CLI output by MWExceptionRenderer.
512 * @param Throwable $e
515 public static function getLogMessage( Throwable
$e ) {
516 $id = WebRequest
::getRequestId();
517 $type = get_class( $e );
518 $message = $e->getMessage();
519 $url = self
::getURL() ?
: '[no req]';
521 if ( $e instanceof DBQueryError
) {
522 $message = "A database query error has occurred. Did you forget to run"
523 . " your application's database schema updater after upgrading"
524 . " or after adding a new extension?\n\nPlease see"
525 . " https://www.mediawiki.org/wiki/Special:MyLanguage/Manual:Upgrading and"
526 . " https://www.mediawiki.org/wiki/Special:MyLanguage/Manual:How_to_debug"
527 . " for more information.\n\n"
531 return "[$id] $url $type: $message";
535 * Get a normalised message for formatting with PSR-3 log event context.
537 * Must be used together with `getLogContext()` to be useful.
540 * @param Throwable $e
543 public static function getLogNormalMessage( Throwable
$e ) {
544 if ( $e instanceof INormalizedException
) {
545 $message = $e->getNormalizedMessage();
547 $message = $e->getMessage();
549 if ( !$e instanceof ErrorException
) {
550 // ErrorException is something we use internally to represent
551 // PHP errors (runtime warnings that aren't thrown or caught),
552 // don't bother putting it in the logs. Let the log message
553 // lead with "PHP Warning: " instead (see ::handleError).
554 $message = get_class( $e ) . ": $message";
557 return "[{reqId}] {exception_url} $message";
561 * @param Throwable $e
564 public static function getPublicLogMessage( Throwable
$e ) {
565 $reqId = WebRequest
::getRequestId();
566 $type = get_class( $e );
567 return '[' . $reqId . '] '
568 . gmdate( 'Y-m-d H:i:s' ) . ': '
569 . 'Fatal exception of type "' . $type . '"';
573 * Get a PSR-3 log event context from a Throwable.
575 * Creates a structured array containing information about the provided
576 * throwable that can be used to augment a log message sent to a PSR-3
580 * @param Throwable $e
581 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
584 public static function getLogContext( Throwable
$e, $catcher = self
::CAUGHT_BY_OTHER
) {
587 'exception_url' => self
::getURL() ?
: '[no req]',
588 // The reqId context key use the same familiar name and value as the top-level field
589 // provided by LogstashFormatter. However, formatters are configurable at run-time,
590 // and their top-level fields are logically separate from context keys and cannot be,
591 // substituted in a message, hence set explicitly here. For WMF users, these may feel,
592 // like the same thing due to Monolog V0 handling, which transmits "fields" and "context",
593 // in the same JSON object (after message formatting).
594 'reqId' => WebRequest
::getRequestId(),
595 'caught_by' => $catcher
597 if ( $e instanceof INormalizedException
) {
598 $context +
= $e->getMessageContext();
604 * Get a structured representation of a Throwable.
606 * Returns an array of structured data (class, message, code, file,
607 * backtrace) derived from the given throwable. The backtrace information
608 * will be redacted as per getRedactedTraceAsArray().
610 * @param Throwable $e
611 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
615 public static function getStructuredExceptionData(
617 $catcher = self
::CAUGHT_BY_OTHER
620 'id' => WebRequest
::getRequestId(),
621 'type' => get_class( $e ),
622 'file' => $e->getFile(),
623 'line' => $e->getLine(),
624 'message' => $e->getMessage(),
625 'code' => $e->getCode(),
626 'url' => self
::getURL() ?
: null,
627 'caught_by' => $catcher
630 if ( $e instanceof ErrorException
&&
631 ( error_reporting() & $e->getSeverity() ) === 0
633 // Flag suppressed errors
634 $data['suppressed'] = true;
637 if ( self
::$logExceptionBacktrace ) {
638 $data['backtrace'] = self
::getRedactedTrace( $e );
641 $previous = $e->getPrevious();
642 if ( $previous !== null ) {
643 $data['previous'] = self
::getStructuredExceptionData( $previous, $catcher );
650 * Serialize a Throwable object to JSON.
652 * The JSON object will have keys 'id', 'file', 'line', 'message', and
653 * 'url'. These keys map to string values, with the exception of 'line',
654 * which is a number, and 'url', which may be either a string URL or
655 * null if the throwable did not occur in the context of serving a web
658 * If $wgLogExceptionBacktrace is true, it will also have a 'backtrace'
659 * key, mapped to the array return value of Throwable::getTrace, but with
660 * each element in each frame's "args" array (if set) replaced with the
661 * argument's class name (if the argument is an object) or type name (if
662 * the argument is a PHP primitive).
664 * @par Sample JSON record ($wgLogExceptionBacktrace = false):
668 * "type": "Exception",
669 * "file": "/var/www/mediawiki/includes/cache/MessageCache.php",
671 * "message": "Example message",
672 * "url": "/wiki/Main_Page"
676 * @par Sample JSON record ($wgLogExceptionBacktrace = true):
680 * "type": "Exception",
681 * "file": "/var/www/mediawiki/includes/cache/MessageCache.php",
683 * "message": "Example message",
684 * "url": "/wiki/Main_Page",
686 * "file": "/var/www/mediawiki/includes/OutputPage.php",
689 * "class": "MessageCache",
697 * @param Throwable $e
698 * @param bool $pretty Add non-significant whitespace to improve readability (default: false).
699 * @param int $escaping Bitfield consisting of FormatJson::.*_OK class constants.
700 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
701 * @return string|false JSON string if successful; false upon failure
703 public static function jsonSerializeException(
707 $catcher = self
::CAUGHT_BY_OTHER
709 return FormatJson
::encode(
710 self
::getStructuredExceptionData( $e, $catcher ),
717 * Log a throwable to the exception log (if enabled).
719 * This method must not assume the throwable is an MWException,
720 * it is also used to handle PHP exceptions or exceptions from other libraries.
723 * @param Throwable $e
724 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
725 * @param array $extraData (since 1.34) Additional data to log
727 public static function logException(
729 $catcher = self
::CAUGHT_BY_OTHER
,
732 if ( !( $e instanceof MWException
) ||
$e->isLoggable() ) {
733 $logger = LoggerFactory
::getInstance( 'exception' );
734 $context = self
::getLogContext( $e, $catcher );
736 $context['extraData'] = $extraData;
739 self
::getLogNormalMessage( $e ),
743 $json = self
::jsonSerializeException( $e, false, FormatJson
::ALL_OK
, $catcher );
744 if ( $json !== false ) {
745 $logger = LoggerFactory
::getInstance( 'exception-json' );
746 $logger->error( $json, [ 'private' => true ] );
749 self
::callLogExceptionHook( $e, false );
754 * Log an exception that wasn't thrown but made to wrap an error.
756 * @param ErrorException $e
757 * @param string $level
758 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
760 private static function logError(
765 // The set_error_handler callback is independent from error_reporting.
766 $suppressed = ( error_reporting() & $e->getSeverity() ) === 0;
768 // Instead of discarding these entirely, give some visibility (but only
769 // when debugging) to errors that were intentionally silenced via
770 // the error silencing operator (@) or Wikimedia\AtEase.
771 // To avoid clobbering Logstash results, set the level to DEBUG
772 // and also send them to a dedicated channel (T193472).
773 $channel = 'silenced-error';
774 $level = LogLevel
::DEBUG
;
778 $logger = LoggerFactory
::getInstance( $channel );
781 self
::getLogNormalMessage( $e ),
782 self
::getLogContext( $e, $catcher )
785 self
::callLogExceptionHook( $e, $suppressed );
789 * Call the LogException hook, suppressing some exceptions.
791 * @param Throwable $e
792 * @param bool $suppressed
794 private static function callLogExceptionHook( Throwable
$e, bool $suppressed ) {
796 ( new HookRunner( MediaWikiServices
::getInstance()->getHookContainer() ) )
797 ->onLogException( $e, $suppressed );
798 } catch ( RecursiveServiceDependencyException
$e ) {
799 // An error from the HookContainer wiring will lead here (T379125)