37 E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR,
49 set_exception_handler(
'MWExceptionHandler::handleException' );
50 set_error_handler(
'MWExceptionHandler::handleError' );
53 self::$reservedMemory = str_repeat(
' ', 16384 );
54 register_shutdown_function(
'MWExceptionHandler::handleFatalError' );
62 global $wgShowExceptionDetails;
74 $message =
"MediaWiki internal error.\n\n";
76 if ( $wgShowExceptionDetails ) {
77 $message .=
'Original exception: ' . self::getLogMessage(
$e ) .
78 "\nBacktrace:\n" . self::getRedactedTraceAsString(
$e ) .
79 "\n\nException caught inside exception handler: " . self::getLogMessage( $e2 ) .
80 "\nBacktrace:\n" . self::getRedactedTraceAsString( $e2 );
82 $message .=
"Exception caught inside exception handler.\n\n" .
83 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
84 "to show detailed debugging information.";
90 self::printError( $message );
92 echo nl2br( htmlspecialchars( $message ) ) .
"\n";
96 $message =
"Exception encountered, of type \"" . get_class(
$e ) .
"\"";
98 if ( $wgShowExceptionDetails ) {
99 $message .=
"\n" . self::getLogMessage(
$e ) .
"\nBacktrace:\n" .
100 self::getRedactedTraceAsString(
$e ) .
"\n";
104 self::printError( $message );
106 echo nl2br( htmlspecialchars( $message ) ) .
"\n";
119 # NOTE: STDERR may not be available, especially if php-cgi is used from the
120 # command line (bug #15602). Try to produce meaningful output anyway. Using
121 # echo may corrupt output to STDOUT though.
122 if ( defined(
'STDERR' ) ) {
123 fwrite( STDERR, $message );
139 if (
$factory->hasMasterChanges() ) {
140 $logger = LoggerFactory::getInstance(
'Bug56269' );
142 'Exception thrown with an uncommited database transaction: ' .
143 self::getLogMessage(
$e ),
144 self::getLogContext(
$e )
146 $factory->rollbackMasterChanges( __METHOD__ );
169 self::rollbackMasterChangesAndLog(
$e );
176 self::logException( $e2 );
179 self::logException(
$e );
205 $level, $message, $file = null,
$line = null
207 if ( in_array( $level, self::$fatalErrorTypes ) ) {
208 return call_user_func_array(
209 'MWExceptionHandler::handleFatalError', func_get_args()
216 case E_RECOVERABLE_ERROR:
217 $levelName =
'Error';
221 case E_COMPILE_WARNING:
223 $levelName =
'Warning';
227 $levelName =
'Notice';
230 $levelName =
'Strict Standards';
233 case E_USER_DEPRECATED:
234 $levelName =
'Deprecated';
237 $levelName =
'Unknown error';
241 $e =
new ErrorException(
"PHP $levelName: $message", 0, $level, $file,
$line );
242 self::logError(
$e,
'error' );
271 $level = null, $message = null, $file = null,
$line = null,
276 self::$reservedMemory = null;
278 if ( $level === null ) {
280 if ( static::$handledFatalCallback ) {
286 $lastError = error_get_last();
287 if ( $lastError !== null ) {
288 $level = $lastError[
'type'];
289 $message = $lastError[
'message'];
290 $file = $lastError[
'file'];
291 $line = $lastError[
'line'];
298 if ( !in_array( $level, self::$fatalErrorTypes ) ) {
304 $msg =
"[{exception_id}] PHP Fatal Error: {$message}";
309 if ( preg_match(
"/Class (undefined: \w+|'\w+' not found)/", $msg ) ) {
314 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.
316 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.
327 $trace = $trace ?: debug_backtrace();
328 $logger = LoggerFactory::getInstance(
'fatal' );
329 $logger->error( $msg, [
331 'class' =>
'ErrorException',
332 'message' =>
"PHP Fatal Error: {$message}",
336 'trace' => static::redactTrace( $trace ),
343 static::$handledFatalCallback =
true;
358 return self::prettyPrintTrace( self::getRedactedTrace(
$e ) );
373 foreach ( $trace
as $level => $frame ) {
374 if ( isset( $frame[
'file'] ) && isset( $frame[
'line'] ) ) {
375 $text .=
"{$pad}#{$level} {$frame['file']}({$frame['line']}): ";
381 $text .=
"{$pad}#{$level} [internal function]: ";
384 if ( isset( $frame[
'class'] ) && isset( $frame[
'type'] ) && isset( $frame[
'function'] ) ) {
385 $text .= $frame[
'class'] . $frame[
'type'] . $frame[
'function'];
386 } elseif ( isset( $frame[
'function'] ) ) {
387 $text .= $frame[
'function'];
389 $text .=
'NO_FUNCTION_GIVEN';
392 if ( isset( $frame[
'args'] ) ) {
393 $text .=
'(' . implode(
', ', $frame[
'args'] ) .
")\n";
400 $text .=
"{$pad}#{$level} {main}";
417 return static::redactTrace(
$e->getTrace() );
431 return array_map(
function ( $frame ) {
432 if ( isset( $frame[
'args'] ) ) {
433 $frame[
'args'] = array_map(
function ( $arg ) {
434 return is_object( $arg ) ? get_class( $arg ) : gettype( $arg );
466 if ( !isset( $wgRequest ) || $wgRequest instanceof
FauxRequest ) {
469 return $wgRequest->getRequestURL();
482 $file =
$e->getFile();
484 $message =
$e->getMessage();
485 $url = self::getURL() ?:
'[no req]';
487 return "[$id] $url $type from line $line of $file: $message";
492 $type = get_class( $e );
493 return '[' . $reqId .
'] '
494 . gmdate(
'Y-m-d H:i:s' ) .
': '
495 .
'Fatal exception of type ' .
$type;
527 global $wgLogExceptionBacktrace;
530 'type' => get_class(
$e ),
531 'file' =>
$e->getFile(),
532 'line' =>
$e->getLine(),
533 'message' =>
$e->getMessage(),
534 'code' =>
$e->getCode(),
535 'url' => self::getURL() ?: null,
538 if (
$e instanceof ErrorException &&
539 ( error_reporting() &
$e->getSeverity() ) === 0
542 $data[
'suppressed'] =
true;
545 if ( $wgLogExceptionBacktrace ) {
546 $data[
'backtrace'] = self::getRedactedTrace(
$e );
549 $previous =
$e->getPrevious();
550 if ( $previous !== null ) {
551 $data[
'previous'] = self::getStructuredExceptionData( $previous );
611 $data = self::getStructuredExceptionData(
$e );
626 $logger = LoggerFactory::getInstance(
'exception' );
628 self::getLogMessage(
$e ),
629 self::getLogContext(
$e )
633 if ( $json !==
false ) {
634 $logger = LoggerFactory::getInstance(
'exception-json' );
635 $logger->error( $json, [
'private' =>
true ] );
649 protected static function logError( ErrorException
$e, $channel ) {
653 $suppressed = ( error_reporting() & $e->getSeverity() ) === 0;
655 $logger = LoggerFactory::getInstance( $channel );
657 self::getLogMessage( $e ),
658 self::getLogContext( $e )
664 if ( $json !==
false ) {
665 $logger = LoggerFactory::getInstance(
"{$channel}-json" );
666 $logger->error( $json, [
'private' =>
true ] );
static printError($message)
Print a message, if possible to STDERR.
static getStructuredExceptionData($e)
Get a structured representation of an Exception.
static handleFatalError($level=null, $message=null, $file=null, $line=null, $context=null, $trace=null)
Dual purpose callback used as both a set_error_handler() callback and a registered shutdown function...
Database error base class.
the array() calling protocol came about after MediaWiki 1.4rc1.
static getRequestId()
Get the unique request ID.
static getLogMessage($e)
Get a message formatting the exception message and its origin.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException'returning false will NOT prevent logging $e
static handleError($level, $message, $file=null, $line=null)
Handler for set_error_handler() callback notifications.
static handleException($e)
Exception handler which simulates the appropriate catch() handling:
when a variable name is used in a it is silently declared as a new local masking the global
wfRandomString($length=32)
Get a random string containing a number of pseudo-random hex characters.
static logError(ErrorException $e, $channel)
Log an exception that wasn't thrown but made to wrap an error.
static getURL()
If the exception occurred in the course of responding to a request, returns the requested URL...
wfDeprecated($function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
static run($event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
static redactTrace(array $trace)
Redact a stacktrace generated by Exception::getTrace(), debug_backtrace() or similar means...
static getRedactedTraceAsString($e)
Generate a string representation of an exception's stack trace.
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
static isCommandLine()
Check whether we are in command line mode or not to report the exception in the correct format...
static rollbackMasterChangesAndLog($e)
If there are any open database transactions, roll them back and log the stack trace of the exception ...
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
wfGetLBFactory()
Get the load balancer factory object.
static getPublicLogMessage(Exception $e)
static installHandler()
Install handlers with PHP.
static getLogContext($e)
Get a PSR-3 log event context from an Exception.
MediaWiki Logger LoggerFactory implements a PSR[0] compatible message logging system Named Psr Log LoggerInterface instances can be obtained from the MediaWiki Logger LoggerFactory::getInstance() static method.MediaWiki\Logger\LoggerFactory expects a class implementing the MediaWiki\Logger\Spi interface to act as a factory for new Psr\Log\LoggerInterface instances.The"Spi"in MediaWiki\Logger\Spi stands for"service provider interface".An SPI is an API intended to be implemented or extended by a third party.This software design pattern is intended to enable framework extension and replaceable components.It is specifically used in the MediaWiki\Logger\LoggerFactory service to allow alternate PSR-3 logging implementations to be easily integrated with MediaWiki.The service provider interface allows the backend logging library to be implemented in multiple ways.The $wgMWLoggerDefaultSpi global provides the classname of the default MediaWiki\Logger\Spi implementation to be loaded at runtime.This can either be the name of a class implementing the MediaWiki\Logger\Spi with a zero argument const ructor or a callable that will return an MediaWiki\Logger\Spi instance.Alternately the MediaWiki\Logger\LoggerFactory MediaWiki Logger LoggerFactory
We ve cleaned up the code here by removing clumps of infrequently used code and moving them off somewhere else It s much easier for someone working with this code to see what s _really_ going on
static jsonSerializeException($e, $pretty=false, $escaping=0)
Serialize an Exception object to JSON.
static getRedactedTrace($e)
Return a copy of an exception's backtrace as an array.
static prettyPrintTrace(array $trace, $pad= '')
Generate a string representation of a stacktrace.
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException'returning false will NOT prevent logging a wrapping ErrorException $suppressed
static logException($e)
Log an exception to the exception log (if enabled).
static report($e)
Report an exception to the user.
static $handledFatalCallback
static getLogId($e)
Get the ID for this exception.
if(is_null($wgLocalTZoffset)) if(!$wgDBerrorLogTZ) $wgRequest
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached one of or reset my talk my contributions etc etc otherwise the built in rate limiting checks are if enabled allows for interception of redirect as a string mapping parameter names to values & $type