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)
 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 ()
 Install handlers with PHP. More...
 
static jsonSerializeException (Throwable $e, $pretty=false, $escaping=0, $catcher=self::CAUGHT_BY_OTHER)
 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)
 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 $fatalErrorTypes
 Error types that, if unhandled, are fatal to the request. More...
 
static $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...
 

Detailed Description

Handler class for MWExceptions.

Definition at line 31 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 521 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 462 of file MWExceptionHandler.php.

References $file, $line, $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 488 of file MWExceptionHandler.php.

References $file, $line, and $type.

◆ getPublicLogMessage()

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

Definition at line 501 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 411 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 argument type or class name.

Parameters
Throwable$e
Returns
string
See also
prettyPrintTrace()

Definition at line 352 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 
)
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().

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

Definition at line 542 of file MWExceptionHandler.php.

References $wgLogExceptionBacktrace, 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 443 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 202 of file MWExceptionHandler.php.

References $file, $line, $wgPropagateErrors, and logError().

◆ 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 183 of file MWExceptionHandler.php.

References report(), and rollbackMasterChangesAndLog().

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 284 of file MWExceptionHandler.php.

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

◆ 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 155 of file MWExceptionHandler.php.

References handleException(), and wfIsCLI().

◆ installHandler()

static MWExceptionHandler::installHandler ( )
static

Install handlers with PHP.

Definition at line 66 of file MWExceptionHandler.php.

◆ jsonSerializeException()

static MWExceptionHandler::jsonSerializeException ( Throwable  $e,
  $pretty = false,
  $escaping = 0,
  $catcher = self::CAUGHT_BY_OTHER 
)
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 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
Returns
string|false JSON string if successful; false upon failure

Definition at line 632 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 690 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 656 of file MWExceptionHandler.php.

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

Referenced by ResourceLoader\applyFilter(), JobRunner\doExecuteJob(), MediaWiki\doPostOutputShutdown(), JobQueueEnqueueUpdate\doUpdate(), MediaWiki\emitBufferedStatsdData(), ChangesListSpecialPage\execute(), DeferredUpdates\jobify(), ResourceLoader\outputErrorAndLog(), MediaWiki\preOutputCommit(), JobQueueGroup\push(), rollbackMasterChangesAndLog(), DeferredUpdates\run(), User\saveSettings(), and MediaWiki\triggerJobs().

◆ 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 364 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 arugment values converted to data types

Definition at line 425 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 97 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

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.23
Parameters
Throwable$e
string$catcherCAUGHT_BY_* class constant indicating what caught the error

Definition at line 125 of file MWExceptionHandler.php.

References logException().

Referenced by JobRunner\doExecuteJob(), MediaWiki\doPostOutputShutdown(), RefreshSecondaryDataUpdate\doUpdate(), handleException(), ApiMain\handleException(), 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 52 of file MWExceptionHandler.php.

◆ $reservedMemory

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

Definition at line 40 of file MWExceptionHandler.php.


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