38 E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR,
50 set_exception_handler(
'MWExceptionHandler::handleException' );
51 set_error_handler(
'MWExceptionHandler::handleError' );
54 self::$reservedMemory = str_repeat(
' ', 16384 );
55 register_shutdown_function(
'MWExceptionHandler::handleFatalError' );
90 $services = MediaWikiServices::getInstance();
91 if (
$services->isServiceDisabled(
'DBLoadBalancerFactory' ) ) {
97 $logger = LoggerFactory::getInstance(
'Bug56269' );
99 'Exception thrown with an uncommited database transaction: ' .
100 self::getLogMessage(
$e ),
101 self::getLogContext(
$e )
104 $lbFactory->rollbackMasterChanges( __METHOD__ );
126 self::rollbackMasterChangesAndLog(
$e );
133 self::logException( $e2 );
136 self::logException(
$e );
162 $level, $message, $file = null,
$line = null
164 if ( in_array( $level, self::$fatalErrorTypes ) ) {
165 return call_user_func_array(
166 'MWExceptionHandler::handleFatalError', func_get_args()
173 case E_RECOVERABLE_ERROR:
174 $levelName =
'Error';
178 case E_COMPILE_WARNING:
180 $levelName =
'Warning';
184 $levelName =
'Notice';
187 $levelName =
'Strict Standards';
190 case E_USER_DEPRECATED:
191 $levelName =
'Deprecated';
194 $levelName =
'Unknown error';
198 $e =
new ErrorException(
"PHP $levelName: $message", 0, $level, $file,
$line );
199 self::logError(
$e,
'error' );
228 $level = null, $message = null, $file = null,
$line = null,
233 self::$reservedMemory = null;
235 if ( $level === null ) {
237 if ( static::$handledFatalCallback ) {
243 $lastError = error_get_last();
244 if ( $lastError !== null ) {
245 $level = $lastError[
'type'];
246 $message = $lastError[
'message'];
247 $file = $lastError[
'file'];
248 $line = $lastError[
'line'];
255 if ( !in_array( $level, self::$fatalErrorTypes ) ) {
261 $msg =
"[{exception_id}] PHP Fatal Error: {$message}";
266 if ( preg_match(
"/Class (undefined: \w+|'\w+' not found)/", $msg ) ) {
271 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.
273 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.
284 $trace = $trace ?: debug_backtrace();
285 $logger = LoggerFactory::getInstance(
'fatal' );
286 $logger->error( $msg, [
288 'class' =>
'ErrorException',
289 'message' =>
"PHP Fatal Error: {$message}",
293 'trace' => static::redactTrace( $trace ),
300 static::$handledFatalCallback =
true;
315 return self::prettyPrintTrace( self::getRedactedTrace(
$e ) );
330 foreach ( $trace
as $level => $frame ) {
331 if ( isset( $frame[
'file'] ) && isset( $frame[
'line'] ) ) {
332 $text .=
"{$pad}#{$level} {$frame['file']}({$frame['line']}): ";
338 $text .=
"{$pad}#{$level} [internal function]: ";
341 if ( isset( $frame[
'class'] ) && isset( $frame[
'type'] ) && isset( $frame[
'function'] ) ) {
342 $text .= $frame[
'class'] . $frame[
'type'] . $frame[
'function'];
343 } elseif ( isset( $frame[
'function'] ) ) {
344 $text .= $frame[
'function'];
346 $text .=
'NO_FUNCTION_GIVEN';
349 if ( isset( $frame[
'args'] ) ) {
350 $text .=
'(' . implode(
', ', $frame[
'args'] ) .
")\n";
357 $text .=
"{$pad}#{$level} {main}";
374 return static::redactTrace(
$e->getTrace() );
388 return array_map(
function ( $frame ) {
389 if ( isset( $frame[
'args'] ) ) {
390 $frame[
'args'] = array_map(
function ( $arg ) {
391 return is_object( $arg ) ? get_class( $arg ) : gettype( $arg );
423 if ( !isset( $wgRequest ) || $wgRequest instanceof
FauxRequest ) {
426 return $wgRequest->getRequestURL();
439 $file =
$e->getFile();
441 $message =
$e->getMessage();
442 $url = self::getURL() ?:
'[no req]';
444 return "[$id] $url $type from line $line of $file: $message";
454 return '[' . $reqId .
'] '
455 . gmdate(
'Y-m-d H:i:s' ) .
': '
456 .
'Fatal exception of type "' .
$type .
'"';
488 global $wgLogExceptionBacktrace;
491 'type' => get_class(
$e ),
492 'file' =>
$e->getFile(),
493 'line' =>
$e->getLine(),
494 'message' =>
$e->getMessage(),
495 'code' =>
$e->getCode(),
496 'url' => self::getURL() ?: null,
499 if (
$e instanceof ErrorException &&
500 ( error_reporting() &
$e->getSeverity() ) === 0
503 $data[
'suppressed'] =
true;
506 if ( $wgLogExceptionBacktrace ) {
507 $data[
'backtrace'] = self::getRedactedTrace(
$e );
510 $previous =
$e->getPrevious();
511 if ( $previous !== null ) {
512 $data[
'previous'] = self::getStructuredExceptionData( $previous );
572 $data = self::getStructuredExceptionData(
$e );
587 $logger = LoggerFactory::getInstance(
'exception' );
589 self::getLogMessage(
$e ),
590 self::getLogContext(
$e )
594 if ( $json !==
false ) {
595 $logger = LoggerFactory::getInstance(
'exception-json' );
596 $logger->error( $json, [
'private' =>
true ] );
610 protected static function logError( ErrorException
$e, $channel ) {
614 $suppressed = ( error_reporting() & $e->getSeverity() ) === 0;
616 $logger = LoggerFactory::getInstance( $channel );
618 self::getLogMessage( $e ),
619 self::getLogContext( $e )
625 if ( $json !==
false ) {
626 $logger = LoggerFactory::getInstance(
"{$channel}-json" );
627 $logger->error( $json, [
'private' =>
true ] );
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
if(!$wgDBerrorLogTZ) $wgRequest
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException'returning false will NOT prevent logging $e
static getPublicLogMessage($e)
static handleError($level, $message, $file=null, $line=null)
Handler for set_error_handler() callback notifications.
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 MediaWikiServices
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 output($e, $mode, $eNew=null)
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 configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title after the basic globals have been set but before ordinary actions take place or wrap services the preferred way to define a new service is the $wgServiceWiringFiles array $services
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 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
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.
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