28use Wikimedia\NormalizedException\INormalizedException;
55 private const FATAL_ERROR_TYPES = [
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 ) {
127 if ( $e instanceof
MWException && $e->hasOverriddenHandler() ) {
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::FATAL_ERROR_TYPES ) ) {
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(
'get_debug_type', $frame[
'args'] );
500 return WebRequest::getGlobalRequestURL();
514 $id = WebRequest::getRequestId();
515 $type = get_class( $e );
516 $message = $e->getMessage();
517 $url = self::getURL() ?:
'[no req]';
520 $message =
"A database query error has occurred. Did you forget to run"
521 .
" your application's database schema updater after upgrading"
522 .
" or after adding a new extension?\n\nPlease see"
523 .
" https://www.mediawiki.org/wiki/Special:MyLanguage/Manual:Upgrading and"
524 .
" https://www.mediawiki.org/wiki/Special:MyLanguage/Manual:How_to_debug"
525 .
" for more information.\n\n"
529 return "[$id] $url $type: $message";
542 if ( $e instanceof INormalizedException ) {
543 $message = $e->getNormalizedMessage();
545 $message = $e->getMessage();
547 if ( !$e instanceof ErrorException ) {
552 $message = get_class( $e ) .
": $message";
555 return "[{reqId}] {exception_url} $message";
563 $reqId = WebRequest::getRequestId();
564 $type = get_class( $e );
565 return '[' . $reqId .
'] '
566 . gmdate(
'Y-m-d H:i:s' ) .
': '
567 .
'Fatal exception of type "' . $type .
'"';
582 public static function getLogContext( Throwable $e, $catcher = self::CAUGHT_BY_OTHER ) {
585 'exception_url' => self::getURL() ?:
'[no req]',
592 'reqId' => WebRequest::getRequestId(),
593 'caught_by' => $catcher
595 if ( $e instanceof INormalizedException ) {
596 $context += $e->getMessageContext();
615 $catcher = self::CAUGHT_BY_OTHER
618 'id' => WebRequest::getRequestId(),
619 'type' => get_class( $e ),
620 'file' => $e->getFile(),
621 'line' => $e->getLine(),
622 'message' => $e->getMessage(),
623 'code' => $e->getCode(),
624 'url' => self::getURL() ?:
null,
625 'caught_by' => $catcher
628 if ( $e instanceof ErrorException &&
629 ( error_reporting() & $e->getSeverity() ) === 0
632 $data[
'suppressed'] =
true;
635 if ( self::$logExceptionBacktrace ) {
636 $data[
'backtrace'] = self::getRedactedTrace( $e );
639 $previous = $e->getPrevious();
640 if ( $previous !==
null ) {
641 $data[
'previous'] = self::getStructuredExceptionData( $previous, $catcher );
705 $catcher = self::CAUGHT_BY_OTHER
707 return FormatJson::encode(
708 self::getStructuredExceptionData( $e, $catcher ),
727 $catcher = self::CAUGHT_BY_OTHER,
730 if ( !( $e instanceof
MWException ) || $e->isLoggable() ) {
731 $logger = LoggerFactory::getInstance(
'exception' );
732 $context = self::getLogContext( $e, $catcher );
734 $context[
'extraData'] = $extraData;
737 self::getLogNormalMessage( $e ),
741 $json = self::jsonSerializeException( $e,
false, FormatJson::ALL_OK, $catcher );
742 if ( $json !==
false ) {
743 $logger = LoggerFactory::getInstance(
'exception-json' );
744 $logger->error( $json, [
'private' =>
true ] );
747 (
new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )->onLogException( $e,
false );
758 private static function logError(
764 $suppressed = ( error_reporting() & $e->getSeverity() ) === 0;
771 $channel =
'silenced-error';
772 $level = LogLevel::DEBUG;
776 $logger = LoggerFactory::getInstance( $channel );
779 self::getLogNormalMessage( $e ),
780 self::getLogContext( $e, $catcher )
783 (
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.
const CAUGHT_BY_HANDLER
Error caught and reported by this exception handler.
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.
const CAUGHT_BY_OTHER
Error reported by direct logException() call.
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 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.
const CAUGHT_BY_ENTRYPOINT
Error caught and reported by a script entry point.
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: