24use Wikimedia\NormalizedException\INormalizedException;
34 public const CAUGHT_BY_HANDLER =
'mwe_handler';
36 public const CAUGHT_BY_ENTRYPOINT =
'entrypoint';
38 public const CAUGHT_BY_OTHER =
'other';
81 set_exception_handler(
'MWExceptionHandler::handleUncaughtException' );
85 set_error_handler(
'MWExceptionHandler::handleError' );
90 self::$reservedMemory = str_repeat(
' ', 16384 );
91 register_shutdown_function(
'MWExceptionHandler::handleFatalError' );
98 protected static function report( Throwable $e ) {
109 }
catch ( Throwable $e2 ) {
128 $catcher = self::CAUGHT_BY_OTHER
130 $services = MediaWikiServices::getInstance();
131 if ( !$services->isServiceDisabled(
'DBLoadBalancerFactory' ) ) {
136 $services->getDBLoadBalancerFactory()->rollbackPrimaryChanges( __METHOD__ );
143 self::logException( $e2, $catcher );
147 self::logException( $e, $catcher );
157 $catcher = self::CAUGHT_BY_OTHER
160 self::rollbackPrimaryChangesAndLog( $e, $catcher );
170 self::handleException( $e, self::CAUGHT_BY_HANDLER );
174 register_shutdown_function(
200 public static function handleException( Throwable $e, $catcher = self::CAUGHT_BY_OTHER ) {
201 self::rollbackPrimaryChangesAndLog( $e, $catcher );
245 case E_COMPILE_WARNING:
246 $prefix =
'PHP Warning: ';
247 $severity = LogLevel::ERROR;
250 $prefix =
'PHP Notice: ';
251 $severity = LogLevel::ERROR;
255 $prefix =
'PHP Notice: ';
256 $severity = LogLevel::WARNING;
260 $prefix =
'PHP Warning: ';
261 $severity = LogLevel::WARNING;
264 $prefix =
'PHP Strict Standards: ';
265 $severity = LogLevel::WARNING;
268 $prefix =
'PHP Deprecated: ';
269 $severity = LogLevel::WARNING;
271 case E_USER_DEPRECATED:
272 $prefix =
'PHP Deprecated: ';
273 $severity = LogLevel::WARNING;
274 $real = MWDebug::parseCallerDescription( $message );
279 $file = $real[
'file'];
280 $line = $real[
'line'];
281 $message = $real[
'message'];
285 $prefix =
'PHP Unknown error: ';
286 $severity = LogLevel::ERROR;
290 $e =
new ErrorException( $prefix . $message, 0, $level,
$file,
$line );
291 self::logError( $e,
'error', $severity, self::CAUGHT_BY_HANDLER );
316 self::$reservedMemory =
null;
318 $lastError = error_get_last();
319 if ( $lastError ===
null ) {
323 $level = $lastError[
'type'];
324 $message = $lastError[
'message'];
325 $file = $lastError[
'file'];
326 $line = $lastError[
'line'];
328 if ( !in_array( $level, self::$fatalErrorTypes ) ) {
334 $url = WebRequest::getGlobalRequestURL();
336 '[{reqId}] {exception_url} PHP Fatal Error',
338 $line ?
" line $line" :
'',
340 $file ?
" $file" :
'',
343 $msg = implode(
'', $msgParts );
346 if ( preg_match(
"/Class '\w+' not found/", $message ) ) {
351MediaWiki 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.
353Please see <a href=
"https://www.mediawiki.org/wiki/Download_from_Git#Fetch_external_libraries">mediawiki.org</a>
for help on installing the required components.
358 $e =
new ErrorException(
"PHP Fatal Error: {$message}", 0, $level,
$file,
$line );
359 $logger = LoggerFactory::getInstance(
'exception' );
360 $logger->error( $msg, self::getLogContext( $e, self::CAUGHT_BY_HANDLER ) );
376 $from =
'from ' . $e->getFile() .
'(' . $e->getLine() .
')' .
"\n";
377 return $from . self::prettyPrintTrace( self::getRedactedTrace( $e ) );
392 foreach ( $trace as $level => $frame ) {
393 if ( isset( $frame[
'file'] ) && isset( $frame[
'line'] ) ) {
394 $text .=
"{$pad}#{$level} {$frame['file']}({$frame['line']}): ";
400 $text .=
"{$pad}#{$level} [internal function]: ";
403 if ( isset( $frame[
'class'] ) && isset( $frame[
'type'] ) && isset( $frame[
'function'] ) ) {
404 $text .= $frame[
'class'] . $frame[
'type'] . $frame[
'function'];
405 } elseif ( isset( $frame[
'function'] ) ) {
406 $text .= $frame[
'function'];
408 $text .=
'NO_FUNCTION_GIVEN';
411 if ( isset( $frame[
'args'] ) ) {
412 $text .=
'(' . implode(
', ', $frame[
'args'] ) .
")\n";
419 $text .=
"{$pad}#{$level} {main}";
436 return static::redactTrace( $e->getTrace() );
450 return array_map(
static function ( $frame ) {
451 if ( isset( $frame[
'args'] ) ) {
452 $frame[
'args'] = array_map(
static function ( $arg ) {
453 return is_object( $arg ) ? get_class( $arg ) : gettype( $arg );
487 $id = WebRequest::getRequestId();
488 $type = get_class( $e );
489 $message = $e->getMessage();
490 $url = self::getURL() ?:
'[no req]';
493 $message =
"A database query error has occurred. Did you forget to run"
494 .
" your application's database schema updater after upgrading"
495 .
" or after adding a new extension?\n\nPlease see"
496 .
" https://www.mediawiki.org/wiki/Special:MyLanguage/Manual:Upgrading and"
497 .
" https://www.mediawiki.org/wiki/Special:MyLanguage/Manual:How_to_debug"
498 .
" for more information.\n\n"
502 return "[$id] $url $type: $message";
515 if ( $e instanceof INormalizedException ) {
516 $message = $e->getNormalizedMessage();
518 $message = $e->getMessage();
520 if ( !$e instanceof ErrorException ) {
525 $message = get_class( $e ) .
": $message";
528 return "[{reqId}] {exception_url} $message";
536 $reqId = WebRequest::getRequestId();
537 $type = get_class( $e );
538 return '[' . $reqId .
'] '
539 . gmdate(
'Y-m-d H:i:s' ) .
': '
540 .
'Fatal exception of type "' .
$type .
'"';
555 public static function getLogContext( Throwable $e, $catcher = self::CAUGHT_BY_OTHER ) {
558 'exception_url' => self::getURL() ?:
'[no req]',
565 'reqId' => WebRequest::getRequestId(),
566 'caught_by' => $catcher
568 if ( $e instanceof INormalizedException ) {
569 $context += $e->getMessageContext();
588 $catcher = self::CAUGHT_BY_OTHER
593 'id' => WebRequest::getRequestId(),
594 'type' => get_class( $e ),
595 'file' => $e->getFile(),
596 'line' => $e->getLine(),
597 'message' => $e->getMessage(),
598 'code' => $e->getCode(),
599 'url' => self::getURL() ?:
null,
600 'caught_by' => $catcher
603 if ( $e instanceof ErrorException &&
604 ( error_reporting() & $e->getSeverity() ) === 0
607 $data[
'suppressed'] =
true;
611 $data[
'backtrace'] = self::getRedactedTrace( $e );
614 $previous = $e->getPrevious();
615 if ( $previous !==
null ) {
616 $data[
'previous'] = self::getStructuredExceptionData( $previous, $catcher );
680 $catcher = self::CAUGHT_BY_OTHER
682 return FormatJson::encode(
683 self::getStructuredExceptionData( $e, $catcher ),
702 $catcher = self::CAUGHT_BY_OTHER,
705 if ( !( $e instanceof
MWException ) || $e->isLoggable() ) {
706 $logger = LoggerFactory::getInstance(
'exception' );
707 $context = self::getLogContext( $e, $catcher );
709 $context[
'extraData'] = $extraData;
712 self::getLogNormalMessage( $e ),
716 $json = self::jsonSerializeException( $e,
false, FormatJson::ALL_OK, $catcher );
717 if ( $json !==
false ) {
718 $logger = LoggerFactory::getInstance(
'exception-json' );
719 $logger->error( $json, [
'private' =>
true ] );
722 Hooks::runner()->onLogException( $e,
false );
743 $suppressed = ( error_reporting() & $e->getSeverity() ) === 0;
744 if ( !$suppressed ) {
745 $logger = LoggerFactory::getInstance( $channel );
748 self::getLogNormalMessage( $e ),
749 self::getLogContext( $e, $catcher )
754 $json = self::jsonSerializeException( $e,
false, FormatJson::ALL_OK, $catcher );
755 if ( $json !==
false ) {
756 $logger = LoggerFactory::getInstance(
"{$channel}-json" );
763 $unfilteredLevel = $suppressed ? LogLevel::DEBUG : $level;
764 $logger->log( $unfilteredLevel, $json, [
'private' =>
true ] );
767 Hooks::runner()->onLogException( $e, $suppressed );
$wgLogExceptionBacktrace
If true, send the exception backtrace to the error log.
$wgPropagateErrors
If true, the MediaWiki error handler passes errors/warnings to the default error handler after loggin...
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that a deprecated feature was used.
wfIsCLI()
Check if we are running from the commandline.
WebRequest clone which takes values from a provided array.
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 getStructuredExceptionData(Throwable $e, $catcher=self::CAUGHT_BY_OTHER)
Get a structured representation of a Throwable.
static rollbackMasterChangesAndLog(Throwable $e, $catcher=self::CAUGHT_BY_OTHER)
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 jsonSerializeException(Throwable $e, $pretty=false, $escaping=0, $catcher=self::CAUGHT_BY_OTHER)
Serialize a Throwable object to JSON.
static logError(ErrorException $e, $channel, $level, $catcher)
Log an exception that wasn't thrown but made to wrap an error.
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 installHandler()
Install handlers with PHP.
static string $reservedMemory
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:
static output(Throwable $e, $mode, Throwable $eNew=null)
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.