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';
53 protected static $fatalErrorTypes = [
69 private static $logExceptionBacktrace =
true;
76 private static $propagateErrors;
86 bool $logExceptionBacktrace =
true,
87 bool $propagateErrors =
true
89 self::$logExceptionBacktrace = $logExceptionBacktrace;
90 self::$propagateErrors = $propagateErrors;
105 set_exception_handler(
'MWExceptionHandler::handleUncaughtException' );
109 set_error_handler(
'MWExceptionHandler::handleError' );
114 self::$reservedMemory = str_repeat(
' ', 16384 );
115 register_shutdown_function(
'MWExceptionHandler::handleFatalError' );
122 protected static function report( Throwable $e ) {
131 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_PRETTY );
133 }
catch ( Throwable $e2 ) {
137 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_RAW, $e2 );
146 private static function rollbackPrimaryChanges() {
147 if ( !MediaWikiServices::hasInstance() ) {
153 $services = MediaWikiServices::getInstance();
154 if ( $services->isServiceDisabled(
'DBLoadBalancerFactory' ) ) {
165 $lbFactory = $services->getDBLoadBalancerFactory();
166 $lbFactory->rollbackPrimaryChanges( __METHOD__ );
167 $lbFactory->flushPrimarySessions( __METHOD__ );
174 self::logException( $e, self::CAUGHT_BY_HANDLER );
189 $catcher = self::CAUGHT_BY_OTHER
191 self::rollbackPrimaryChanges();
193 self::logException( $e, $catcher );
203 $catcher = self::CAUGHT_BY_OTHER
206 self::rollbackPrimaryChangesAndLog( $e, $catcher );
216 self::handleException( $e, self::CAUGHT_BY_HANDLER );
220 register_shutdown_function(
246 public static function handleException( Throwable $e, $catcher = self::CAUGHT_BY_OTHER ) {
247 self::rollbackPrimaryChangesAndLog( $e, $catcher );
289 case E_COMPILE_WARNING:
290 $prefix =
'PHP Warning: ';
291 $severity = LogLevel::ERROR;
294 $prefix =
'PHP Notice: ';
295 $severity = LogLevel::ERROR;
299 $prefix =
'PHP Notice: ';
300 $severity = LogLevel::WARNING;
304 $prefix =
'PHP Warning: ';
305 $severity = LogLevel::WARNING;
308 $prefix =
'PHP Strict Standards: ';
309 $severity = LogLevel::WARNING;
312 $prefix =
'PHP Deprecated: ';
313 $severity = LogLevel::WARNING;
315 case E_USER_DEPRECATED:
316 $prefix =
'PHP Deprecated: ';
317 $severity = LogLevel::WARNING;
318 $real = MWDebug::parseCallerDescription( $message );
323 $file = $real[
'file'];
324 $line = $real[
'line'];
325 $message = $real[
'message'];
329 $prefix =
'PHP Unknown error: ';
330 $severity = LogLevel::ERROR;
335 $e =
new ErrorException( $prefix . $message, 0, $level,
$file,
$line );
336 self::logError( $e,
'error', $severity, self::CAUGHT_BY_HANDLER );
341 return !( self::$propagateErrors || ini_get(
'track_errors' ) );
361 self::$reservedMemory =
null;
363 $lastError = error_get_last();
364 if ( $lastError ===
null ) {
368 $level = $lastError[
'type'];
369 $message = $lastError[
'message'];
370 $file = $lastError[
'file'];
371 $line = $lastError[
'line'];
373 if ( !in_array( $level, self::$fatalErrorTypes ) ) {
380 '[{reqId}] {exception_url} PHP Fatal Error',
382 $line ?
" line $line" :
'',
384 $file ?
" $file" :
'',
387 $msg = implode(
'', $msgParts );
390 if ( preg_match(
"/Class '\w+' not found/", $message ) ) {
395MediaWiki 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.
397Please see <a href=
"https://www.mediawiki.org/wiki/Download_from_Git#Fetch_external_libraries">mediawiki.org</a>
for help on installing the required components.
402 $e =
new ErrorException(
"PHP Fatal Error: {$message}", 0, $level,
$file,
$line );
403 $logger = LoggerFactory::getInstance(
'exception' );
404 $logger->error( $msg, self::getLogContext( $e, self::CAUGHT_BY_HANDLER ) );
420 $from =
'from ' . $e->getFile() .
'(' . $e->getLine() .
')' .
"\n";
421 return $from . self::prettyPrintTrace( self::getRedactedTrace( $e ) );
436 foreach ( $trace as $level => $frame ) {
437 if ( isset( $frame[
'file'] ) && isset( $frame[
'line'] ) ) {
438 $text .=
"{$pad}#{$level} {$frame['file']}({$frame['line']}): ";
444 $text .=
"{$pad}#{$level} [internal function]: ";
447 if ( isset( $frame[
'class'] ) && isset( $frame[
'type'] ) && isset( $frame[
'function'] ) ) {
448 $text .= $frame[
'class'] . $frame[
'type'] . $frame[
'function'];
450 $text .= $frame[
'function'] ??
'NO_FUNCTION_GIVEN';
453 if ( isset( $frame[
'args'] ) ) {
454 $text .=
'(' . implode(
', ', $frame[
'args'] ) .
")\n";
461 $text .=
"{$pad}#{$level} {main}";
478 return static::redactTrace( $e->getTrace() );
492 return array_map(
static function ( $frame ) {
493 if ( isset( $frame[
'args'] ) ) {
494 $frame[
'args'] = array_map(
static function ( $arg ) {
495 return is_object( $arg ) ? get_class( $arg ) : gettype( $arg );
529 $id = WebRequest::getRequestId();
530 $type = get_class( $e );
531 $message = $e->getMessage();
532 $url = self::getURL() ?:
'[no req]';
535 $message =
"A database query error has occurred. Did you forget to run"
536 .
" your application's database schema updater after upgrading"
537 .
" or after adding a new extension?\n\nPlease see"
538 .
" https://www.mediawiki.org/wiki/Special:MyLanguage/Manual:Upgrading and"
539 .
" https://www.mediawiki.org/wiki/Special:MyLanguage/Manual:How_to_debug"
540 .
" for more information.\n\n"
544 return "[$id] $url $type: $message";
557 if ( $e instanceof INormalizedException ) {
558 $message = $e->getNormalizedMessage();
560 $message = $e->getMessage();
562 if ( !$e instanceof ErrorException ) {
567 $message = get_class( $e ) .
": $message";
570 return "[{reqId}] {exception_url} $message";
578 $reqId = WebRequest::getRequestId();
579 $type = get_class( $e );
580 return '[' . $reqId .
'] '
581 . gmdate(
'Y-m-d H:i:s' ) .
': '
582 .
'Fatal exception of type "' .
$type .
'"';
597 public static function getLogContext( Throwable $e, $catcher = self::CAUGHT_BY_OTHER ) {
600 'exception_url' => self::getURL() ?:
'[no req]',
607 'reqId' => WebRequest::getRequestId(),
608 'caught_by' => $catcher
610 if ( $e instanceof INormalizedException ) {
611 $context += $e->getMessageContext();
630 $catcher = self::CAUGHT_BY_OTHER
633 'id' => WebRequest::getRequestId(),
634 'type' => get_class( $e ),
635 'file' => $e->getFile(),
636 'line' => $e->getLine(),
637 'message' => $e->getMessage(),
638 'code' => $e->getCode(),
639 'url' => self::getURL() ?:
null,
640 'caught_by' => $catcher
643 if ( $e instanceof ErrorException &&
644 ( error_reporting() & $e->getSeverity() ) === 0
647 $data[
'suppressed'] =
true;
650 if ( self::$logExceptionBacktrace ) {
651 $data[
'backtrace'] = self::getRedactedTrace( $e );
654 $previous = $e->getPrevious();
655 if ( $previous !==
null ) {
656 $data[
'previous'] = self::getStructuredExceptionData( $previous, $catcher );
720 $catcher = self::CAUGHT_BY_OTHER
722 return FormatJson::encode(
723 self::getStructuredExceptionData( $e, $catcher ),
742 $catcher = self::CAUGHT_BY_OTHER,
745 if ( !( $e instanceof
MWException ) || $e->isLoggable() ) {
746 $logger = LoggerFactory::getInstance(
'exception' );
747 $context = self::getLogContext( $e, $catcher );
749 $context[
'extraData'] = $extraData;
752 self::getLogNormalMessage( $e ),
756 $json = self::jsonSerializeException( $e,
false, FormatJson::ALL_OK, $catcher );
757 if ( $json !==
false ) {
758 $logger = LoggerFactory::getInstance(
'exception-json' );
759 $logger->error( $json, [
'private' =>
true ] );
762 Hooks::runner()->onLogException( $e,
false );
774 private static function logError(
783 $suppressed = ( error_reporting() & $e->getSeverity() ) === 0;
784 if ( !$suppressed ) {
785 $logger = LoggerFactory::getInstance( $channel );
788 self::getLogNormalMessage( $e ),
789 self::getLogContext( $e, $catcher )
794 $json = self::jsonSerializeException( $e,
false, FormatJson::ALL_OK, $catcher );
795 if ( $json !==
false ) {
796 $logger = LoggerFactory::getInstance(
"{$channel}-json" );
803 $unfilteredLevel = $suppressed ? LogLevel::DEBUG : $level;
804 $logger->log( $unfilteredLevel, $json, [
'private' =>
true ] );
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.
static runner()
Get a HookRunner instance for calling hooks using the new interfaces.
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 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 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:
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.