3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
21 use MediaWiki\Logger\LoggerFactory
;
22 use MediaWiki\MediaWikiServices
;
24 use Wikimedia\Rdbms\DBError
;
27 * Handler class for MWExceptions
30 class MWExceptionHandler
{
31 const CAUGHT_BY_HANDLER
= 'mwe_handler'; // error reported by this exception handler
32 const CAUGHT_BY_OTHER
= 'other'; // error reported by direct logException() call
35 * @var string $reservedMemory
37 protected static $reservedMemory;
39 * @var array $fatalErrorTypes
41 protected static $fatalErrorTypes = [
42 E_ERROR
, E_PARSE
, E_CORE_ERROR
, E_COMPILE_ERROR
, E_USER_ERROR
,
43 /* HHVM's FATAL_ERROR level */ 16777217,
46 * @var bool $handledFatalCallback
48 protected static $handledFatalCallback = false;
51 * Install handlers with PHP.
53 public static function installHandler() {
54 set_exception_handler( 'MWExceptionHandler::handleUncaughtException' );
55 set_error_handler( 'MWExceptionHandler::handleError' );
57 // Reserve 16k of memory so we can report OOM fatals
58 self
::$reservedMemory = str_repeat( ' ', 16384 );
59 register_shutdown_function( 'MWExceptionHandler::handleFatalError' );
63 * Report an exception to the user
64 * @param Exception|Throwable $e
66 protected static function report( $e ) {
68 // Try and show the exception prettily, with the normal skin infrastructure
69 if ( $e instanceof MWException
) {
70 // Delegate to MWException until all subclasses are handled by
71 // MWExceptionRenderer and MWException::report() has been
75 MWExceptionRenderer
::output( $e, MWExceptionRenderer
::AS_PRETTY
);
77 } catch ( Exception
$e2 ) {
78 // Exception occurred from within exception handler
79 // Show a simpler message for the original exception,
80 // don't try to invoke report()
81 MWExceptionRenderer
::output( $e, MWExceptionRenderer
::AS_RAW
, $e2 );
86 * Roll back any open database transactions and log the stack trace of the exception
88 * This method is used to attempt to recover from exceptions
91 * @param Exception|Throwable $e
93 public static function rollbackMasterChangesAndLog( $e ) {
94 $services = MediaWikiServices
::getInstance();
95 if ( !$services->isServiceDisabled( 'DBLoadBalancerFactory' ) ) {
96 // Rollback DBs to avoid transaction notices. This might fail
97 // to rollback some databases due to connection issues or exceptions.
98 // However, any sane DB driver will rollback implicitly anyway.
100 $services->getDBLoadBalancerFactory()->rollbackMasterChanges( __METHOD__
);
101 } catch ( DBError
$e2 ) {
102 // If the DB is unreacheable, rollback() will throw an error
103 // and the error report() method might need messages from the DB,
104 // which would result in an exception loop. PHP may escalate such
105 // errors to "Exception thrown without a stack frame" fatals, but
106 // it's better to be explicit here.
107 self
::logException( $e2, self
::CAUGHT_BY_HANDLER
);
111 self
::logException( $e, self
::CAUGHT_BY_HANDLER
);
115 * Callback to use with PHP's set_exception_handler.
118 * @param Exception|Throwable $e
120 public static function handleUncaughtException( $e ) {
121 self
::handleException( $e );
123 // Make sure we don't claim success on exit for CLI scripts (T177414)
125 register_shutdown_function(
134 * Exception handler which simulates the appropriate catch() handling:
138 * } catch ( Exception $e ) {
140 * } catch ( Exception $e ) {
141 * echo $e->__toString();
145 * @param Exception|Throwable $e
147 public static function handleException( $e ) {
148 self
::rollbackMasterChangesAndLog( $e );
153 * Handler for set_error_handler() callback notifications.
155 * Receive a callback from the interpreter for a raised error, create an
156 * ErrorException, and log the exception to the 'error' logging
157 * channel(s). If the raised error is a fatal error type (only under HHVM)
158 * delegate to handleFatalError() instead.
162 * @param int $level Error level raised
163 * @param string $message
164 * @param string $file
170 public static function handleError(
171 $level, $message, $file = null, $line = null
173 global $wgPropagateErrors;
175 if ( in_array( $level, self
::$fatalErrorTypes ) ) {
176 return call_user_func_array(
177 'MWExceptionHandler::handleFatalError', func_get_args()
181 // Map error constant to error name (reverse-engineer PHP error
184 case E_RECOVERABLE_ERROR
:
185 $levelName = 'Error';
186 $severity = LogLevel
::ERROR
;
190 case E_COMPILE_WARNING
:
192 $levelName = 'Warning';
193 $severity = LogLevel
::WARNING
;
197 $levelName = 'Notice';
198 $severity = LogLevel
::INFO
;
201 $levelName = 'Strict Standards';
202 $severity = LogLevel
::DEBUG
;
205 case E_USER_DEPRECATED
:
206 $levelName = 'Deprecated';
207 $severity = LogLevel
::INFO
;
210 $levelName = 'Unknown error';
211 $severity = LogLevel
::ERROR
;
215 $e = new ErrorException( "PHP $levelName: $message", 0, $level, $file, $line );
216 self
::logError( $e, 'error', $severity );
218 // If $wgPropagateErrors is true return false so PHP shows/logs the error normally.
219 // Ignore $wgPropagateErrors if the error should break execution, or track_errors is set
220 // (which means someone is counting on regular PHP error handling behavior).
221 return !( $wgPropagateErrors ||
$level == E_RECOVERABLE_ERROR ||
ini_get( 'track_errors' ) );
225 * Dual purpose callback used as both a set_error_handler() callback and
226 * a registered shutdown function. Receive a callback from the interpreter
227 * for a raised error or system shutdown, check for a fatal error, and log
228 * to the 'fatal' logging channel.
230 * Special handling is included for missing class errors as they may
231 * indicate that the user needs to install 3rd-party libraries via
232 * Composer or other means.
236 * @param int $level Error level raised
237 * @param string $message Error message
238 * @param string $file File that error was raised in
239 * @param int $line Line number error was raised at
240 * @param array $context Active symbol table point of error
241 * @param array $trace Backtrace at point of error (undocumented HHVM
243 * @return bool Always returns false
245 public static function handleFatalError(
246 $level = null, $message = null, $file = null, $line = null,
247 $context = null, $trace = null
249 // Free reserved memory so that we have space to process OOM
251 self
::$reservedMemory = null;
253 if ( $level === null ) {
254 // Called as a shutdown handler, get data from error_get_last()
255 if ( static::$handledFatalCallback ) {
256 // Already called once (probably as an error handler callback
257 // under HHVM) so don't log again.
261 $lastError = error_get_last();
262 if ( $lastError !== null ) {
263 $level = $lastError['type'];
264 $message = $lastError['message'];
265 $file = $lastError['file'];
266 $line = $lastError['line'];
273 if ( !in_array( $level, self
::$fatalErrorTypes ) ) {
274 // Only interested in fatal errors, others should have been
275 // handled by MWExceptionHandler::handleError
279 $msg = "[{exception_id}] PHP Fatal Error: {$message}";
281 // Look at message to see if this is a class not found failure
282 // HHVM: Class undefined: foo
283 // PHP5: Class 'foo' not found
284 if ( preg_match( "/Class (undefined: \w+|'\w+' not found)/", $msg ) ) {
285 // phpcs:disable Generic.Files.LineLength
289 MediaWiki 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.
291 Please see <a href="https://www.mediawiki.org/wiki/Download_from_Git#Fetch_external_libraries">mediawiki.org</a> for help on installing the required components.
296 // We can't just create an exception and log it as it is likely that
297 // the interpreter has unwound the stack already. If that is true the
298 // stacktrace we would get would be functionally empty. If however we
299 // have been called as an error handler callback *and* HHVM is in use
300 // we will have been provided with a useful stacktrace that we can
302 $trace = $trace ?
: debug_backtrace();
303 $logger = LoggerFactory
::getInstance( 'fatal' );
304 $logger->error( $msg, [
305 'fatal_exception' => [
306 'class' => ErrorException
::class,
307 'message' => "PHP Fatal Error: {$message}",
311 'trace' => static::redactTrace( $trace ),
313 'exception_id' => wfRandomString( 8 ),
314 'caught_by' => self
::CAUGHT_BY_HANDLER
317 // Remember call so we don't double process via HHVM's fatal
318 // notifications and the shutdown hook behavior
319 static::$handledFatalCallback = true;
324 * Generate a string representation of an exception's stack trace
326 * Like Exception::getTraceAsString, but replaces argument values with
327 * argument type or class name.
329 * @param Exception|Throwable $e
331 * @see prettyPrintTrace()
333 public static function getRedactedTraceAsString( $e ) {
334 return self
::prettyPrintTrace( self
::getRedactedTrace( $e ) );
338 * Generate a string representation of a stacktrace.
340 * @param array $trace
341 * @param string $pad Constant padding to add to each line of trace
345 public static function prettyPrintTrace( array $trace, $pad = '' ) {
349 foreach ( $trace as $level => $frame ) {
350 if ( isset( $frame['file'] ) && isset( $frame['line'] ) ) {
351 $text .= "{$pad}#{$level} {$frame['file']}({$frame['line']}): ";
353 // 'file' and 'line' are unset for calls via call_user_func
354 // (T57634) This matches behaviour of
355 // Exception::getTraceAsString to instead display "[internal
357 $text .= "{$pad}#{$level} [internal function]: ";
360 if ( isset( $frame['class'] ) && isset( $frame['type'] ) && isset( $frame['function'] ) ) {
361 $text .= $frame['class'] . $frame['type'] . $frame['function'];
362 } elseif ( isset( $frame['function'] ) ) {
363 $text .= $frame['function'];
365 $text .= 'NO_FUNCTION_GIVEN';
368 if ( isset( $frame['args'] ) ) {
369 $text .= '(' . implode( ', ', $frame['args'] ) . ")\n";
376 $text .= "{$pad}#{$level} {main}";
382 * Return a copy of an exception's backtrace as an array.
384 * Like Exception::getTrace, but replaces each element in each frame's
385 * argument array with the name of its class (if the element is an object)
386 * or its type (if the element is a PHP primitive).
389 * @param Exception|Throwable $e
392 public static function getRedactedTrace( $e ) {
393 return static::redactTrace( $e->getTrace() );
397 * Redact a stacktrace generated by Exception::getTrace(),
398 * debug_backtrace() or similar means. Replaces each element in each
399 * frame's argument array with the name of its class (if the element is an
400 * object) or its type (if the element is a PHP primitive).
403 * @param array $trace Stacktrace
404 * @return array Stacktrace with arugment values converted to data types
406 public static function redactTrace( array $trace ) {
407 return array_map( function ( $frame ) {
408 if ( isset( $frame['args'] ) ) {
409 $frame['args'] = array_map( function ( $arg ) {
410 return is_object( $arg ) ?
get_class( $arg ) : gettype( $arg );
418 * Get the ID for this exception.
420 * The ID is saved so that one can match the one output to the user (when
421 * $wgShowExceptionDetails is set to false), to the entry in the debug log.
424 * @deprecated since 1.27: Exception IDs are synonymous with request IDs.
425 * @param Exception|Throwable $e
428 public static function getLogId( $e ) {
429 wfDeprecated( __METHOD__
, '1.27' );
430 return WebRequest
::getRequestId();
434 * If the exception occurred in the course of responding to a request,
435 * returns the requested URL. Otherwise, returns false.
438 * @return string|false
440 public static function getURL() {
442 if ( !isset( $wgRequest ) ||
$wgRequest instanceof FauxRequest
) {
445 return $wgRequest->getRequestURL();
449 * Get a message formatting the exception message and its origin.
452 * @param Exception|Throwable $e
455 public static function getLogMessage( $e ) {
456 $id = WebRequest
::getRequestId();
457 $type = get_class( $e );
458 $file = $e->getFile();
459 $line = $e->getLine();
460 $message = $e->getMessage();
461 $url = self
::getURL() ?
: '[no req]';
463 return "[$id] $url $type from line $line of $file: $message";
467 * Get a normalised message for formatting with PSR-3 log event context.
469 * Must be used together with `getLogContext()` to be useful.
472 * @param Exception|Throwable $e
475 public static function getLogNormalMessage( $e ) {
476 $type = get_class( $e );
477 $file = $e->getFile();
478 $line = $e->getLine();
479 $message = $e->getMessage();
481 return "[{exception_id}] {exception_url} $type from line $line of $file: $message";
485 * @param Exception|Throwable $e
488 public static function getPublicLogMessage( $e ) {
489 $reqId = WebRequest
::getRequestId();
490 $type = get_class( $e );
491 return '[' . $reqId . '] '
492 . gmdate( 'Y-m-d H:i:s' ) . ': '
493 . 'Fatal exception of type "' . $type . '"';
497 * Get a PSR-3 log event context from an Exception.
499 * Creates a structured array containing information about the provided
500 * exception that can be used to augment a log message sent to a PSR-3
503 * @param Exception|Throwable $e
504 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
507 public static function getLogContext( $e, $catcher = self
::CAUGHT_BY_OTHER
) {
510 'exception_id' => WebRequest
::getRequestId(),
511 'exception_url' => self
::getURL() ?
: '[no req]',
512 'caught_by' => $catcher
517 * Get a structured representation of an Exception.
519 * Returns an array of structured data (class, message, code, file,
520 * backtrace) derived from the given exception. The backtrace information
521 * will be redacted as per getRedactedTraceAsArray().
523 * @param Exception|Throwable $e
524 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
528 public static function getStructuredExceptionData( $e, $catcher = self
::CAUGHT_BY_OTHER
) {
529 global $wgLogExceptionBacktrace;
532 'id' => WebRequest
::getRequestId(),
533 'type' => get_class( $e ),
534 'file' => $e->getFile(),
535 'line' => $e->getLine(),
536 'message' => $e->getMessage(),
537 'code' => $e->getCode(),
538 'url' => self
::getURL() ?
: null,
539 'caught_by' => $catcher
542 if ( $e instanceof ErrorException
&&
543 ( error_reporting() & $e->getSeverity() ) === 0
545 // Flag surpressed errors
546 $data['suppressed'] = true;
549 if ( $wgLogExceptionBacktrace ) {
550 $data['backtrace'] = self
::getRedactedTrace( $e );
553 $previous = $e->getPrevious();
554 if ( $previous !== null ) {
555 $data['previous'] = self
::getStructuredExceptionData( $previous, $catcher );
562 * Serialize an Exception object to JSON.
564 * The JSON object will have keys 'id', 'file', 'line', 'message', and
565 * 'url'. These keys map to string values, with the exception of 'line',
566 * which is a number, and 'url', which may be either a string URL or or
567 * null if the exception did not occur in the context of serving a web
570 * If $wgLogExceptionBacktrace is true, it will also have a 'backtrace'
571 * key, mapped to the array return value of Exception::getTrace, but with
572 * each element in each frame's "args" array (if set) replaced with the
573 * argument's class name (if the argument is an object) or type name (if
574 * the argument is a PHP primitive).
576 * @par Sample JSON record ($wgLogExceptionBacktrace = false):
580 * "type": "MWException",
581 * "file": "/var/www/mediawiki/includes/cache/MessageCache.php",
583 * "message": "Non-string key given",
584 * "url": "/wiki/Main_Page"
588 * @par Sample JSON record ($wgLogExceptionBacktrace = true):
592 * "type": "MWException",
593 * "file": "/vagrant/mediawiki/includes/cache/MessageCache.php",
595 * "message": "Non-string key given",
596 * "url": "/wiki/Main_Page",
598 * "file": "/vagrant/mediawiki/extensions/VisualEditor/VisualEditor.hooks.php",
601 * "class": "MessageCache",
609 * @param Exception|Throwable $e
610 * @param bool $pretty Add non-significant whitespace to improve readability (default: false).
611 * @param int $escaping Bitfield consisting of FormatJson::.*_OK class constants.
612 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
613 * @return string|false JSON string if successful; false upon failure
615 public static function jsonSerializeException(
616 $e, $pretty = false, $escaping = 0, $catcher = self
::CAUGHT_BY_OTHER
618 return FormatJson
::encode(
619 self
::getStructuredExceptionData( $e, $catcher ),
626 * Log an exception to the exception log (if enabled).
628 * This method must not assume the exception is an MWException,
629 * it is also used to handle PHP exceptions or exceptions from other libraries.
632 * @param Exception|Throwable $e
633 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
635 public static function logException( $e, $catcher = self
::CAUGHT_BY_OTHER
) {
636 if ( !( $e instanceof MWException
) ||
$e->isLoggable() ) {
637 $logger = LoggerFactory
::getInstance( 'exception' );
639 self
::getLogNormalMessage( $e ),
640 self
::getLogContext( $e, $catcher )
643 $json = self
::jsonSerializeException( $e, false, FormatJson
::ALL_OK
, $catcher );
644 if ( $json !== false ) {
645 $logger = LoggerFactory
::getInstance( 'exception-json' );
646 $logger->error( $json, [ 'private' => true ] );
649 Hooks
::run( 'LogException', [ $e, false ] );
654 * Log an exception that wasn't thrown but made to wrap an error.
657 * @param ErrorException $e
658 * @param string $channel
659 * @param string $level
661 protected static function logError(
662 ErrorException
$e, $channel, $level = LogLevel
::ERROR
664 $catcher = self
::CAUGHT_BY_HANDLER
;
665 // The set_error_handler callback is independent from error_reporting.
666 // Filter out unwanted errors manually (e.g. when
667 // Wikimedia\suppressWarnings is active).
668 $suppressed = ( error_reporting() & $e->getSeverity() ) === 0;
669 if ( !$suppressed ) {
670 $logger = LoggerFactory
::getInstance( $channel );
673 self
::getLogNormalMessage( $e ),
674 self
::getLogContext( $e, $catcher )
678 // Include all errors in the json log (surpressed errors will be flagged)
679 $json = self
::jsonSerializeException( $e, false, FormatJson
::ALL_OK
, $catcher );
680 if ( $json !== false ) {
681 $logger = LoggerFactory
::getInstance( "{$channel}-json" );
682 $logger->log( $level, $json, [ 'private' => true ] );
685 Hooks
::run( 'LogException', [ $e, $suppressed ] );