26use Wikimedia\NormalizedException\INormalizedException;
36 public const CAUGHT_BY_HANDLER =
'mwe_handler';
38 public const CAUGHT_BY_ENTRYPOINT =
'entrypoint';
40 public const CAUGHT_BY_OTHER =
'other';
55 protected static $fatalErrorTypes = [
71 private static $logExceptionBacktrace =
true;
78 private static $propagateErrors;
88 bool $logExceptionBacktrace =
true,
89 bool $propagateErrors =
true
91 self::$logExceptionBacktrace = $logExceptionBacktrace;
92 self::$propagateErrors = $propagateErrors;
107 set_exception_handler( [ self::class,
'handleUncaughtException' ] );
111 set_error_handler( [ self::class,
'handleError' ] );
116 self::$reservedMemory = str_repeat(
' ', 16384 );
117 register_shutdown_function( [ self::class,
'handleFatalError' ] );
124 protected static function report( Throwable $e ) {
133 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_PRETTY );
135 }
catch ( Throwable $e2 ) {
139 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_RAW, $e2 );
148 private static function rollbackPrimaryChanges() {
149 if ( !MediaWikiServices::hasInstance() ) {
155 $services = MediaWikiServices::getInstance();
156 if ( $services->isServiceDisabled(
'DBLoadBalancerFactory' ) ) {
167 $lbFactory = $services->getDBLoadBalancerFactory();
168 $lbFactory->rollbackPrimaryChanges( __METHOD__ );
169 $lbFactory->flushPrimarySessions( __METHOD__ );
176 self::logException( $e, self::CAUGHT_BY_HANDLER );
191 $catcher = self::CAUGHT_BY_OTHER
193 self::rollbackPrimaryChanges();
195 self::logException( $e, $catcher );
205 self::handleException( $e, self::CAUGHT_BY_HANDLER );
209 register_shutdown_function(
235 public static function handleException( Throwable $e, $catcher = self::CAUGHT_BY_OTHER ) {
236 self::rollbackPrimaryChangesAndLog( $e, $catcher );
278 case E_COMPILE_WARNING:
279 $prefix =
'PHP Warning: ';
280 $severity = LogLevel::ERROR;
283 $prefix =
'PHP Notice: ';
284 $severity = LogLevel::ERROR;
288 $prefix =
'PHP Notice: ';
289 $severity = LogLevel::WARNING;
293 $prefix =
'PHP Warning: ';
294 $severity = LogLevel::WARNING;
297 $prefix =
'PHP Strict Standards: ';
298 $severity = LogLevel::WARNING;
301 $prefix =
'PHP Deprecated: ';
302 $severity = LogLevel::WARNING;
304 case E_USER_DEPRECATED:
305 $prefix =
'PHP Deprecated: ';
306 $severity = LogLevel::WARNING;
307 $real = MWDebug::parseCallerDescription( $message );
312 $file = $real[
'file'];
313 $line = $real[
'line'];
314 $message = $real[
'message'];
318 $prefix =
'PHP Unknown error: ';
319 $severity = LogLevel::ERROR;
324 $e =
new ErrorException( $prefix . $message, 0, $level, $file, $line );
325 self::logError( $e, $severity, self::CAUGHT_BY_HANDLER );
330 return !( self::$propagateErrors || ini_get(
'track_errors' ) );
350 self::$reservedMemory =
null;
352 $lastError = error_get_last();
353 if ( $lastError ===
null ) {
357 $level = $lastError[
'type'];
358 $message = $lastError[
'message'];
359 $file = $lastError[
'file'];
360 $line = $lastError[
'line'];
362 if ( !in_array( $level, self::$fatalErrorTypes ) ) {
369 '[{reqId}] {exception_url} PHP Fatal Error',
370 ( $line || $file ) ?
' from' :
'',
371 $line ?
" line $line" :
'',
372 ( $line && $file ) ?
' of' :
'',
373 $file ?
" $file" :
'',
376 $msg = implode(
'', $msgParts );
379 if ( preg_match(
"/Class '\w+' not found/", $message ) ) {
384MediaWiki 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.
386Please see <a href=
"https://www.mediawiki.org/wiki/Download_from_Git#Fetch_external_libraries">mediawiki.org</a>
for help on installing the required components.
391 $e =
new ErrorException(
"PHP Fatal Error: {$message}", 0, $level, $file, $line );
392 $logger = LoggerFactory::getInstance(
'exception' );
393 $logger->error( $msg, self::getLogContext( $e, self::CAUGHT_BY_HANDLER ) );
409 $from =
'from ' . $e->getFile() .
'(' . $e->getLine() .
')' .
"\n";
410 return $from . self::prettyPrintTrace( self::getRedactedTrace( $e ) );
425 foreach ( $trace as $level => $frame ) {
426 if ( isset( $frame[
'file'] ) && isset( $frame[
'line'] ) ) {
427 $text .=
"{$pad}#{$level} {$frame['file']}({$frame['line']}): ";
433 $text .=
"{$pad}#{$level} [internal function]: ";
436 if ( isset( $frame[
'class'] ) && isset( $frame[
'type'] ) && isset( $frame[
'function'] ) ) {
437 $text .= $frame[
'class'] . $frame[
'type'] . $frame[
'function'];
439 $text .= $frame[
'function'] ??
'NO_FUNCTION_GIVEN';
442 if ( isset( $frame[
'args'] ) ) {
443 $text .=
'(' . implode(
', ', $frame[
'args'] ) .
")\n";
450 $text .=
"{$pad}#{$level} {main}";
467 return static::redactTrace( $e->getTrace() );
481 return array_map(
static function ( $frame ) {
482 if ( isset( $frame[
'args'] ) ) {
483 $frame[
'args'] = array_map(
static function ( $arg ) {
484 return is_object( $arg ) ? get_class( $arg ) : gettype( $arg );
502 return WebRequest::getGlobalRequestURL();
517 $id = WebRequest::getRequestId();
518 $type = get_class( $e );
519 $message = $e->getMessage();
520 $url = self::getURL() ?:
'[no req]';
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";
545 if ( $e instanceof INormalizedException ) {
546 $message = $e->getNormalizedMessage();
548 $message = $e->getMessage();
550 if ( !$e instanceof ErrorException ) {
555 $message = get_class( $e ) .
": $message";
558 return "[{reqId}] {exception_url} $message";
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 .
'"';
585 public static function getLogContext( Throwable $e, $catcher = self::CAUGHT_BY_OTHER ) {
588 'exception_url' => self::getURL() ?:
'[no req]',
595 'reqId' => WebRequest::getRequestId(),
596 'caught_by' => $catcher
598 if ( $e instanceof INormalizedException ) {
599 $context += $e->getMessageContext();
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
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 );
708 $catcher = self::CAUGHT_BY_OTHER
710 return FormatJson::encode(
711 self::getStructuredExceptionData( $e, $catcher ),
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 (
new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )->onLogException( $e,
false );
761 private static function logError(
767 $suppressed = ( error_reporting() & $e->getSeverity() ) === 0;
774 $channel =
'silenced-error';
775 $level = LogLevel::DEBUG;
779 $logger = LoggerFactory::getInstance( $channel );
782 self::getLogNormalMessage( $e ),
783 self::getLogContext( $e, $catcher )
787 $json = self::jsonSerializeException( $e,
false, FormatJson::ALL_OK, $catcher );
788 if ( $json !==
false ) {
789 $logger = LoggerFactory::getInstance(
"error-json" );
790 $logger->log( $level, $json, [
'private' =>
true ] );
793 (
new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )->onLogException( $e, $suppressed );
wfIsCLI()
Check if we are running from the commandline.
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 installHandler(bool $logExceptionBacktrace=true, bool $propagateErrors=true)
Install handlers with PHP.
static getStructuredExceptionData(Throwable $e, $catcher=self::CAUGHT_BY_OTHER)
Get a structured representation of a Throwable.
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 string null $reservedMemory
static jsonSerializeException(Throwable $e, $pretty=false, $escaping=0, $catcher=self::CAUGHT_BY_OTHER)
Serialize a Throwable object to JSON.
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 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: