28use Wikimedia\NormalizedException\INormalizedException;
32use Wikimedia\Services\RecursiveServiceDependencyException;
57 private const FATAL_ERROR_TYPES = [
73 private static $logExceptionBacktrace =
true;
80 private static $propagateErrors;
90 bool $logExceptionBacktrace =
true,
91 bool $propagateErrors =
true
93 self::$logExceptionBacktrace = $logExceptionBacktrace;
94 self::$propagateErrors = $propagateErrors;
109 set_exception_handler( [ self::class,
'handleUncaughtException' ] );
113 set_error_handler( [ self::class,
'handleError' ] );
118 self::$reservedMemory = str_repeat(
' ', 16384 );
119 register_shutdown_function( [ self::class,
'handleFatalError' ] );
126 protected static function report( Throwable $e ) {
129 if ( $e instanceof
MWException && $e->hasOverriddenHandler() ) {
135 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_PRETTY );
137 }
catch ( Throwable $e2 ) {
141 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_RAW, $e2 );
150 private static function rollbackPrimaryChanges() {
151 if ( !MediaWikiServices::hasInstance() ) {
157 $services = MediaWikiServices::getInstance();
158 $lbFactory = $services->peekService(
'DBLoadBalancerFactory' );
159 '@phan-var LBFactory $lbFactory';
170 $lbFactory->rollbackPrimaryChanges( __METHOD__ );
171 $lbFactory->flushPrimarySessions( __METHOD__ );
178 self::logException( $e, self::CAUGHT_BY_HANDLER );
193 $catcher = self::CAUGHT_BY_OTHER
195 self::rollbackPrimaryChanges();
197 self::logException( $e, $catcher );
207 self::handleException( $e, self::CAUGHT_BY_HANDLER );
211 register_shutdown_function(
237 public static function handleException( Throwable $e, $catcher = self::CAUGHT_BY_OTHER ) {
238 self::rollbackPrimaryChangesAndLog( $e, $catcher );
280 case E_COMPILE_WARNING:
281 $prefix =
'PHP Warning: ';
282 $severity = LogLevel::ERROR;
285 $prefix =
'PHP Notice: ';
286 $severity = LogLevel::ERROR;
290 $prefix =
'PHP Notice: ';
291 $severity = LogLevel::WARNING;
295 $prefix =
'PHP Warning: ';
296 $severity = LogLevel::WARNING;
299 $prefix =
'PHP Strict Standards: ';
300 $severity = LogLevel::WARNING;
303 $prefix =
'PHP Deprecated: ';
304 $severity = LogLevel::WARNING;
306 case E_USER_DEPRECATED:
307 $prefix =
'PHP Deprecated: ';
308 $severity = LogLevel::WARNING;
309 $real = MWDebug::parseCallerDescription( $message );
314 $file = $real[
'file'];
315 $line = $real[
'line'];
316 $message = $real[
'message'];
320 $prefix =
'PHP Unknown error: ';
321 $severity = LogLevel::ERROR;
326 $e =
new ErrorException( $prefix . $message, 0, $level, $file, $line );
327 self::logError( $e, $severity, self::CAUGHT_BY_HANDLER );
332 return !( self::$propagateErrors || ini_get(
'track_errors' ) );
352 self::$reservedMemory =
null;
354 $lastError = error_get_last();
355 if ( $lastError ===
null ) {
359 $level = $lastError[
'type'];
360 $message = $lastError[
'message'];
361 $file = $lastError[
'file'];
362 $line = $lastError[
'line'];
364 if ( !in_array( $level, self::FATAL_ERROR_TYPES ) ) {
371 '[{reqId}] {exception_url} PHP Fatal Error',
372 ( $line || $file ) ?
' from' :
'',
373 $line ?
" line $line" :
'',
374 ( $line && $file ) ?
' of' :
'',
375 $file ?
" $file" :
'',
378 $msg = implode(
'', $msgParts );
381 if ( preg_match(
"/Class '\w+' not found/", $message ) ) {
386MediaWiki 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.
388Please see <a href=
"https://www.mediawiki.org/wiki/Download_from_Git#Fetch_external_libraries">mediawiki.org</a>
for help on installing the required components.
393 $e =
new ErrorException(
"PHP Fatal Error: {$message}", 0, $level, $file, $line );
394 $logger = LoggerFactory::getInstance(
'exception' );
395 $logger->error( $msg, self::getLogContext( $e, self::CAUGHT_BY_HANDLER ) );
411 $from =
'from ' . $e->getFile() .
'(' . $e->getLine() .
')' .
"\n";
412 return $from . self::prettyPrintTrace( self::getRedactedTrace( $e ) );
427 foreach ( $trace as $level => $frame ) {
428 if ( isset( $frame[
'file'] ) && isset( $frame[
'line'] ) ) {
429 $text .=
"{$pad}#{$level} {$frame['file']}({$frame['line']}): ";
435 $text .=
"{$pad}#{$level} [internal function]: ";
438 if ( isset( $frame[
'class'] ) && isset( $frame[
'type'] ) && isset( $frame[
'function'] ) ) {
439 $text .= $frame[
'class'] . $frame[
'type'] . $frame[
'function'];
441 $text .= $frame[
'function'] ??
'NO_FUNCTION_GIVEN';
444 if ( isset( $frame[
'args'] ) ) {
445 $text .=
'(' . implode(
', ', $frame[
'args'] ) .
")\n";
452 $text .=
"{$pad}#{$level} {main}";
469 return static::redactTrace( $e->getTrace() );
483 return array_map(
static function ( $frame ) {
484 if ( isset( $frame[
'args'] ) ) {
485 $frame[
'args'] = array_map(
'get_debug_type', $frame[
'args'] );
502 return WebRequest::getGlobalRequestURL();
516 $id = WebRequest::getRequestId();
517 $type = get_class( $e );
518 $message = $e->getMessage();
519 $url = self::getURL() ?:
'[no req]';
522 $message =
"A database query error has occurred. Did you forget to run"
523 .
" your application's database schema updater after upgrading"
524 .
" or after adding a new extension?\n\nPlease see"
525 .
" https://www.mediawiki.org/wiki/Special:MyLanguage/Manual:Upgrading and"
526 .
" https://www.mediawiki.org/wiki/Special:MyLanguage/Manual:How_to_debug"
527 .
" for more information.\n\n"
531 return "[$id] $url $type: $message";
544 if ( $e instanceof INormalizedException ) {
545 $message = $e->getNormalizedMessage();
547 $message = $e->getMessage();
549 if ( !$e instanceof ErrorException ) {
554 $message = get_class( $e ) .
": $message";
557 return "[{reqId}] {exception_url} $message";
565 $reqId = WebRequest::getRequestId();
566 $type = get_class( $e );
567 return '[' . $reqId .
'] '
568 . gmdate(
'Y-m-d H:i:s' ) .
': '
569 .
'Fatal exception of type "' . $type .
'"';
584 public static function getLogContext( Throwable $e, $catcher = self::CAUGHT_BY_OTHER ) {
587 'exception_url' => self::getURL() ?:
'[no req]',
594 'reqId' => WebRequest::getRequestId(),
595 'caught_by' => $catcher
597 if ( $e instanceof INormalizedException ) {
598 $context += $e->getMessageContext();
617 $catcher = self::CAUGHT_BY_OTHER
620 'id' => WebRequest::getRequestId(),
621 'type' => get_class( $e ),
622 'file' => $e->getFile(),
623 'line' => $e->getLine(),
624 'message' => $e->getMessage(),
625 'code' => $e->getCode(),
626 'url' => self::getURL() ?:
null,
627 'caught_by' => $catcher
630 if ( $e instanceof ErrorException &&
631 ( error_reporting() & $e->getSeverity() ) === 0
634 $data[
'suppressed'] =
true;
637 if ( self::$logExceptionBacktrace ) {
638 $data[
'backtrace'] = self::getRedactedTrace( $e );
641 $previous = $e->getPrevious();
642 if ( $previous !==
null ) {
643 $data[
'previous'] = self::getStructuredExceptionData( $previous, $catcher );
707 $catcher = self::CAUGHT_BY_OTHER
709 return FormatJson::encode(
710 self::getStructuredExceptionData( $e, $catcher ),
729 $catcher = self::CAUGHT_BY_OTHER,
732 if ( !( $e instanceof
MWException ) || $e->isLoggable() ) {
733 $logger = LoggerFactory::getInstance(
'exception' );
734 $context = self::getLogContext( $e, $catcher );
736 $context[
'extraData'] = $extraData;
739 self::getLogNormalMessage( $e ),
743 $json = self::jsonSerializeException( $e,
false, FormatJson::ALL_OK, $catcher );
744 if ( $json !==
false ) {
745 $logger = LoggerFactory::getInstance(
'exception-json' );
746 $logger->error( $json, [
'private' =>
true ] );
749 self::callLogExceptionHook( $e,
false );
760 private static function logError(
766 $suppressed = ( error_reporting() & $e->getSeverity() ) === 0;
773 $channel =
'silenced-error';
774 $level = LogLevel::DEBUG;
778 $logger = LoggerFactory::getInstance( $channel );
781 self::getLogNormalMessage( $e ),
782 self::getLogContext( $e, $catcher )
785 self::callLogExceptionHook( $e, $suppressed );
794 private static function callLogExceptionHook( Throwable $e,
bool $suppressed ) {
796 (
new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )
797 ->onLogException( $e, $suppressed );
798 }
catch ( RecursiveServiceDependencyException $e ) {
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: