MediaWiki  master
MWExceptionHandler Class Reference

Handler class for MWExceptions. More...

Static Public Member Functions

static getLogContext (Throwable $e, $catcher=self::CAUGHT_BY_OTHER)
 Get a PSR-3 log event context from a Throwable. More...
 
static getLogMessage (Throwable $e)
 Get a message formatting the throwable message and its origin. More...
 
static getLogNormalMessage (Throwable $e)
 Get a normalised message for formatting with PSR-3 log event context. More...
 
static getPublicLogMessage (Throwable $e)
 
static getRedactedTrace (Throwable $e)
 Return a copy of a throwable's backtrace as an array. More...
 
static getRedactedTraceAsString (Throwable $e)
 Generate a string representation of a throwable's stack trace. More...
 
static getStructuredExceptionData (Throwable $e, $catcher=self::CAUGHT_BY_OTHER, ?bool $includeBacktrace=null)
 Get a structured representation of a Throwable. More...
 
static getURL ()
 If the exception occurred in the course of responding to a request, returns the requested URL. More...
 
static handleError ( $level, $message, $file=null, $line=null)
 Handler for set_error_handler() callback notifications. More...
 
static handleException (Throwable $e, $catcher=self::CAUGHT_BY_OTHER)
 Exception handler which simulates the appropriate catch() handling: More...
 
static handleFatalError ()
 Callback used as a registered shutdown function. More...
 
static handleUncaughtException (Throwable $e)
 Callback to use with PHP's set_exception_handler. More...
 
static installHandler (bool $logExceptionBacktrace=true, bool $propagateErrors=true)
 Install handlers with PHP. More...
 
static jsonSerializeException (Throwable $e, $pretty=false, $escaping=0, $catcher=self::CAUGHT_BY_OTHER, ?bool $includeBacktrace=null)
 Serialize a Throwable object to JSON. More...
 
static logException (Throwable $e, $catcher=self::CAUGHT_BY_OTHER, $extraData=[])
 Log a throwable to the exception log (if enabled). More...
 
static prettyPrintTrace (array $trace, $pad='')
 Generate a string representation of a stacktrace. More...
 
static redactTrace (array $trace)
 Redact a stacktrace generated by Throwable::getTrace(), debug_backtrace() or similar means. More...
 
static rollbackMasterChangesAndLog (Throwable $e, $catcher=self::CAUGHT_BY_OTHER)
 
static rollbackPrimaryChangesAndLog (Throwable $e, $catcher=self::CAUGHT_BY_OTHER)
 Roll back any open database transactions and log the stack trace of the throwable. More...
 

Static Protected Member Functions

static report (Throwable $e)
 Report a throwable to the user. More...
 

Static Protected Attributes

static array $fatalErrorTypes
 Error types that, if unhandled, are fatal to the request. More...
 
static string null $reservedMemory
 

Static Private Member Functions

static logError (ErrorException $e, $channel, $level, $catcher)
 Log an exception that wasn't thrown but made to wrap an error. More...
 

Static Private Attributes

static bool $logExceptionBacktrace = true
 Whether exception data should include a backtrace. More...
 
static bool $propagateErrors
 Whether to propagate errors to PHP's built-in handler. More...
 

Detailed Description

Handler class for MWExceptions.

Definition at line 32 of file MWExceptionHandler.php.

Member Function Documentation

◆ getLogContext()

static MWExceptionHandler::getLogContext ( Throwable  $e,
  $catcher = self::CAUGHT_BY_OTHER 
)
static

Get a PSR-3 log event context from a Throwable.

Creates a structured array containing information about the provided throwable that can be used to augment a log message sent to a PSR-3 logger.

Since
1.26
Parameters
Throwable$e
string$catcherCAUGHT_BY_* class constant indicating what caught the error
Returns
array

Definition at line 580 of file MWExceptionHandler.php.

References WebRequest\getRequestId(), and getURL().

Referenced by logException().

◆ getLogMessage()

static MWExceptionHandler::getLogMessage ( Throwable  $e)
static

Get a message formatting the throwable message and its origin.

Despite the method name, this is not used for logging. It is only used for HTML or CLI output, by MWExceptionRenderer and MWException::getText, respectively.

Since
1.22
Parameters
Throwable$e
Returns
string

Definition at line 511 of file MWExceptionHandler.php.

References $type, WebRequest\getRequestId(), and getURL().

Referenced by ResourceLoader\formatExceptionNoComment(), MWException\getHTML(), MWExceptionRenderer\getHTML(), MWException\getText(), MWExceptionRenderer\getText(), and MWExceptionRenderer\output().

◆ getLogNormalMessage()

static MWExceptionHandler::getLogNormalMessage ( Throwable  $e)
static

Get a normalised message for formatting with PSR-3 log event context.

Must be used together with getLogContext() to be useful.

Since
1.30
Parameters
Throwable$e
Returns
string

Definition at line 539 of file MWExceptionHandler.php.

◆ getPublicLogMessage()

static MWExceptionHandler::getPublicLogMessage ( Throwable  $e)
static
Parameters
Throwable$e
Returns
string

Definition at line 560 of file MWExceptionHandler.php.

References $type, and WebRequest\getRequestId().

Referenced by ResourceLoader\formatExceptionNoComment(), and MWExceptionRenderer\output().

◆ getRedactedTrace()

static MWExceptionHandler::getRedactedTrace ( Throwable  $e)
static

Return a copy of a throwable's backtrace as an array.

Like Throwable::getTrace, but replaces each element in each frame's argument array with the name of its class (if the element is an object) or its type (if the element is a PHP primitive).

Since
1.22
Parameters
Throwable$e
Returns
array

Definition at line 460 of file MWExceptionHandler.php.

Referenced by MediaWiki\Logger\LegacyLogger\format(), and getStructuredExceptionData().

◆ getRedactedTraceAsString()

static MWExceptionHandler::getRedactedTraceAsString ( Throwable  $e)
static

Generate a string representation of a throwable's stack trace.

Like Throwable::getTraceAsString, but replaces argument values with their type or class name, and prepends the start line of the throwable.

Parameters
Throwable$e
Returns
string
See also
prettyPrintTrace()

Definition at line 400 of file MWExceptionHandler.php.

References prettyPrintTrace().

Referenced by ResourceLoader\formatExceptionNoComment(), MWException\getHTML(), MWExceptionRenderer\getHTML(), MWException\getText(), MWExceptionRenderer\getText(), MediaWiki\Logger\Monolog\LogstashFormatter\normalizeException(), MWExceptionRenderer\output(), and ApiMain\substituteResultWithError().

◆ getStructuredExceptionData()

static MWExceptionHandler::getStructuredExceptionData ( Throwable  $e,
  $catcher = self::CAUGHT_BY_OTHER,
?bool  $includeBacktrace = null 
)
static

Get a structured representation of a Throwable.

Returns an array of structured data (class, message, code, file, backtrace) derived from the given throwable. The backtrace information will be redacted as per getRedactedTraceAsArray().

Parameters
Throwable$e
string$catcherCAUGHT_BY_* class constant indicating what caught the error
bool | null$includeBacktraceWhether to include a backtrace. If null, the value of $includeBacktrace that was provided to installHandler() will be used.
Returns
array
Since
1.26

Definition at line 615 of file MWExceptionHandler.php.

References $logExceptionBacktrace, getRedactedTrace(), WebRequest\getRequestId(), and getURL().

Referenced by MediaWiki\Rest\ResponseFactory\createFromException().

◆ getURL()

static MWExceptionHandler::getURL ( )
static

If the exception occurred in the course of responding to a request, returns the requested URL.

Otherwise, returns false.

Since
1.23
Returns
string|false

Definition at line 492 of file MWExceptionHandler.php.

References $wgRequest.

Referenced by MWException\getHTML(), MWExceptionRenderer\getHTML(), getLogContext(), getLogMessage(), and getStructuredExceptionData().

◆ handleError()

static MWExceptionHandler::handleError (   $level,
  $message,
  $file = null,
  $line = null 
)
static

Handler for set_error_handler() callback notifications.

Receive a callback from the interpreter for a raised error, create an ErrorException, and log the exception to the 'error' logging channel(s).

Since
1.25
Parameters
int$levelError level raised
string$message
string | null$file
int | null$line
Returns
bool

Definition at line 245 of file MWExceptionHandler.php.

References $file, $line, logError(), and MWDebug\parseCallerDescription().

◆ handleException()

static MWExceptionHandler::handleException ( Throwable  $e,
  $catcher = self::CAUGHT_BY_OTHER 
)
static

Exception handler which simulates the appropriate catch() handling:

try { ... } catch ( Exception $e ) { $e->report(); } catch ( Exception $e ) { echo $e->__toString(); }

Since
1.25
Parameters
Throwable$e
string$catcherCAUGHT_BY_* class constant indicating what caught the error

Definition at line 226 of file MWExceptionHandler.php.

References report(), and rollbackPrimaryChangesAndLog().

Referenced by handleUncaughtException(), and MediaWiki\run().

◆ handleFatalError()

static MWExceptionHandler::handleFatalError ( )
static

Callback used as a registered shutdown function.

This is used as callback from the interpreter at system shutdown. If the last error was not a recoverable error that we already reported, and log as fatal exception.

Special handling is included for missing class errors as they may indicate that the user needs to install 3rd-party libraries via Composer or other means.

Since
1.25
Returns
bool Always returns false

Definition at line 338 of file MWExceptionHandler.php.

References $file, $line, and WebRequest\getGlobalRequestURL().

◆ handleUncaughtException()

static MWExceptionHandler::handleUncaughtException ( Throwable  $e)
static

Callback to use with PHP's set_exception_handler.

Since
1.31
Parameters
Throwable$e

Definition at line 195 of file MWExceptionHandler.php.

References handleException(), and wfIsCLI().

◆ installHandler()

static MWExceptionHandler::installHandler ( bool  $logExceptionBacktrace = true,
bool  $propagateErrors = true 
)
static

Install handlers with PHP.

Access: internal
Parameters
bool$logExceptionBacktraceWhether error handlers should include a backtrace in the log.
bool$propagateErrorsWhether errors should be propagated to PHP's built-in handler.

Definition at line 85 of file MWExceptionHandler.php.

References $logExceptionBacktrace, and $propagateErrors.

◆ jsonSerializeException()

static MWExceptionHandler::jsonSerializeException ( Throwable  $e,
  $pretty = false,
  $escaping = 0,
  $catcher = self::CAUGHT_BY_OTHER,
?bool  $includeBacktrace = null 
)
static

Serialize a Throwable object to JSON.

The JSON object will have keys 'id', 'file', 'line', 'message', and 'url'. These keys map to string values, with the exception of 'line', which is a number, and 'url', which may be either a string URL or null if the throwable did not occur in the context of serving a web request.

If $wgLogExceptionBacktrace is true, it will also have a 'backtrace' key, mapped to the array return value of Throwable::getTrace, but with each element in each frame's "args" array (if set) replaced with the argument's class name (if the argument is an object) or type name (if the argument is a PHP primitive).

Sample JSON record ($wgLogExceptionBacktrace = false):
{
"id": "c41fb419",
"type": "MWException",
"file": "/var/www/mediawiki/includes/cache/MessageCache.php",
"line": 704,
"message": "Non-string key given",
"url": "/wiki/Main_Page"
}
Sample JSON record ($wgLogExceptionBacktrace = true):
{
"id": "dc457938",
"type": "MWException",
"file": "/vagrant/mediawiki/includes/cache/MessageCache.php",
"line": 704,
"message": "Non-string key given",
"url": "/wiki/Main_Page",
"backtrace": [{
"file": "/vagrant/mediawiki/extensions/VisualEditor/VisualEditor.hooks.php",
"line": 80,
"function": "get",
"class": "MessageCache",
"type": "->",
"args": ["array"]
}]
}
Since
1.23
Parameters
Throwable$e
bool$prettyAdd non-significant whitespace to improve readability (default: false).
int$escapingBitfield consisting of FormatJson::.*_OK class constants.
string$catcherCAUGHT_BY_* class constant indicating what caught the error
bool | null$includeBacktraceWhether to include a backtrace. If null, the value of $includeBacktrace that was provided to installHandler() will be used.
Returns
string|false JSON string if successful; false upon failure

Definition at line 711 of file MWExceptionHandler.php.

References FormatJson\encode().

Referenced by logError(), and logException().

◆ logError()

static MWExceptionHandler::logError ( ErrorException  $e,
  $channel,
  $level,
  $catcher 
)
staticprivate

Log an exception that wasn't thrown but made to wrap an error.

Parameters
ErrorException$e
string$channel
string$level
string$catcherCAUGHT_BY_* class constant indicating what caught the error

Definition at line 770 of file MWExceptionHandler.php.

References FormatJson\ALL_OK, jsonSerializeException(), and Hooks\runner().

Referenced by handleError().

◆ logException()

static MWExceptionHandler::logException ( Throwable  $e,
  $catcher = self::CAUGHT_BY_OTHER,
  $extraData = [] 
)
static

Log a throwable to the exception log (if enabled).

This method must not assume the throwable is an MWException, it is also used to handle PHP exceptions or exceptions from other libraries.

Since
1.22
Parameters
Throwable$e
string$catcherCAUGHT_BY_* class constant indicating what caught the error
array$extraData(since 1.34) Additional data to log

Definition at line 736 of file MWExceptionHandler.php.

References FormatJson\ALL_OK, getLogContext(), jsonSerializeException(), and Hooks\runner().

Referenced by JobRunner\doExecuteJob(), JobQueueEnqueueUpdate\doUpdate(), MediaWiki\emitBufferedStatsdData(), ChangesListSpecialPage\execute(), DeferredUpdates\jobify(), ResourceLoader\outputErrorAndLog(), MediaWiki\preOutputCommit(), JobQueueGroup\push(), rollbackPrimaryChangesAndLog(), User\saveSettings(), and SpecialUploadStash\showUploads().

◆ prettyPrintTrace()

static MWExceptionHandler::prettyPrintTrace ( array  $trace,
  $pad = '' 
)
static

Generate a string representation of a stacktrace.

Since
1.26
Parameters
array$trace
string$padConstant padding to add to each line of trace
Returns
string

Definition at line 413 of file MWExceptionHandler.php.

Referenced by MediaWiki\Logger\LegacyLogger\format(), getRedactedTraceAsString(), and MediaWiki\Logger\Monolog\LineFormatter\normalizeExceptionArray().

◆ redactTrace()

static MWExceptionHandler::redactTrace ( array  $trace)
static

Redact a stacktrace generated by Throwable::getTrace(), debug_backtrace() or similar means.

Replaces each element in each frame's argument array with the name of its class (if the element is an object) or its type (if the element is a PHP primitive).

Since
1.26
Parameters
array$traceStacktrace
Returns
array Stacktrace with argument values converted to data types

Definition at line 474 of file MWExceptionHandler.php.

Referenced by MediaWiki\Logger\Monolog\LineFormatter\exceptionAsArray().

◆ report()

static MWExceptionHandler::report ( Throwable  $e)
staticprotected

Report a throwable to the user.

Parameters
Throwable$e

Definition at line 122 of file MWExceptionHandler.php.

References MWExceptionRenderer\AS_PRETTY, MWExceptionRenderer\AS_RAW, and MWExceptionRenderer\output().

Referenced by handleException().

◆ rollbackMasterChangesAndLog()

static MWExceptionHandler::rollbackMasterChangesAndLog ( Throwable  $e,
  $catcher = self::CAUGHT_BY_OTHER 
)
static
Deprecated:
since 1.37; please use rollbackPrimaryChangesAndLog() instead.
Parameters
Throwable$e
string$catcherCAUGHT_BY_* class constant indicating what caught the error

Definition at line 181 of file MWExceptionHandler.php.

References rollbackPrimaryChangesAndLog(), and wfDeprecated().

◆ rollbackPrimaryChangesAndLog()

static MWExceptionHandler::rollbackPrimaryChangesAndLog ( Throwable  $e,
  $catcher = self::CAUGHT_BY_OTHER 
)
static

Roll back any open database transactions and log the stack trace of the throwable.

This method is used to attempt to recover from exceptions

Since
1.37
Parameters
Throwable$e
string$catcherCAUGHT_BY_* class constant indicating what caught the error

Definition at line 150 of file MWExceptionHandler.php.

References logException().

Referenced by JobRunner\doExecuteJob(), MediaWiki\doPostOutputShutdown(), RefreshSecondaryDataUpdate\doUpdate(), ApiMain\handleException(), handleException(), MediaWiki\Rest\Reporter\MWErrorReporter\reportError(), rollbackMasterChangesAndLog(), AssembleUploadChunksJob\run(), and PublishStashedFileJob\run().

Member Data Documentation

◆ $fatalErrorTypes

array MWExceptionHandler::$fatalErrorTypes
staticprotected
Initial value:
= [
E_ERROR,
E_PARSE,
E_CORE_ERROR,
E_COMPILE_ERROR,
E_USER_ERROR,
E_RECOVERABLE_ERROR,
]

Error types that, if unhandled, are fatal to the request.

These error types may be thrown as Error objects, which implement Throwable (but not Exception).

The user will be shown an HTTP 500 Internal Server Error. As such, these should be sent to MediaWiki's "exception" channel. Normally, the error handler logs them to the "error" channel.

Definition at line 53 of file MWExceptionHandler.php.

◆ $logExceptionBacktrace

bool MWExceptionHandler::$logExceptionBacktrace = true
staticprivate

Whether exception data should include a backtrace.

Definition at line 69 of file MWExceptionHandler.php.

Referenced by getStructuredExceptionData(), and installHandler().

◆ $propagateErrors

bool MWExceptionHandler::$propagateErrors
staticprivate

Whether to propagate errors to PHP's built-in handler.

Definition at line 76 of file MWExceptionHandler.php.

Referenced by installHandler().

◆ $reservedMemory

string null MWExceptionHandler::$reservedMemory
staticprotected
Initial value:
=
public const CAUGHT_BY_OTHER 'other'

Definition at line 41 of file MWExceptionHandler.php.


The documentation for this class was generated from the following file: