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::handleException' );
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 * If there are any open database transactions, roll them back and log
87 * the stack trace of the exception that should have been caught so the
88 * transaction could be aborted properly.
91 * @param Exception|Throwable $e
93 public static function rollbackMasterChangesAndLog( $e ) {
94 $services = MediaWikiServices
::getInstance();
95 if ( $services->isServiceDisabled( 'DBLoadBalancerFactory' ) ) {
99 $lbFactory = $services->getDBLoadBalancerFactory();
100 if ( $lbFactory->hasMasterChanges() ) {
101 $logger = LoggerFactory
::getInstance( 'Bug56269' );
103 'Exception thrown with an uncommited database transaction: ' .
104 self
::getLogMessage( $e ),
105 self
::getLogContext( $e )
108 $lbFactory->rollbackMasterChanges( __METHOD__
);
112 * Exception handler which simulates the appropriate catch() handling:
116 * } catch ( Exception $e ) {
118 * } catch ( Exception $e ) {
119 * echo $e->__toString();
123 * @param Exception|Throwable $e
125 public static function handleException( $e ) {
127 // Rollback DBs to avoid transaction notices. This may fail
128 // to rollback some DB due to connection issues or exceptions.
129 // However, any sane DB driver will rollback implicitly anyway.
130 self
::rollbackMasterChangesAndLog( $e );
131 } catch ( DBError
$e2 ) {
132 // If the DB is unreacheable, rollback() will throw an error
133 // and the error report() method might need messages from the DB,
134 // which would result in an exception loop. PHP may escalate such
135 // errors to "Exception thrown without a stack frame" fatals, but
136 // it's better to be explicit here.
137 self
::logException( $e2, self
::CAUGHT_BY_HANDLER
);
140 self
::logException( $e, self
::CAUGHT_BY_HANDLER
);
143 // Exit value should be nonzero for the benefit of shell jobs
148 * Handler for set_error_handler() callback notifications.
150 * Receive a callback from the interpreter for a raised error, create an
151 * ErrorException, and log the exception to the 'error' logging
152 * channel(s). If the raised error is a fatal error type (only under HHVM)
153 * delegate to handleFatalError() instead.
157 * @param int $level Error level raised
158 * @param string $message
159 * @param string $file
165 public static function handleError(
166 $level, $message, $file = null, $line = null
168 if ( in_array( $level, self
::$fatalErrorTypes ) ) {
169 return call_user_func_array(
170 'MWExceptionHandler::handleFatalError', func_get_args()
174 // Map error constant to error name (reverse-engineer PHP error
177 case E_RECOVERABLE_ERROR
:
178 $levelName = 'Error';
179 $severity = LogLevel
::ERROR
;
183 case E_COMPILE_WARNING
:
185 $levelName = 'Warning';
186 $severity = LogLevel
::WARNING
;
190 $levelName = 'Notice';
191 $severity = LogLevel
::INFO
;
194 $levelName = 'Strict Standards';
195 $severity = LogLevel
::DEBUG
;
198 case E_USER_DEPRECATED
:
199 $levelName = 'Deprecated';
200 $severity = LogLevel
::INFO
;
203 $levelName = 'Unknown error';
204 $severity = LogLevel
::ERROR
;
208 $e = new ErrorException( "PHP $levelName: $message", 0, $level, $file, $line );
209 self
::logError( $e, 'error', $severity );
211 // This handler is for logging only. Return false will instruct PHP
212 // to continue regular handling.
217 * Dual purpose callback used as both a set_error_handler() callback and
218 * a registered shutdown function. Receive a callback from the interpreter
219 * for a raised error or system shutdown, check for a fatal error, and log
220 * to the 'fatal' logging channel.
222 * Special handling is included for missing class errors as they may
223 * indicate that the user needs to install 3rd-party libraries via
224 * Composer or other means.
228 * @param int $level Error level raised
229 * @param string $message Error message
230 * @param string $file File that error was raised in
231 * @param int $line Line number error was raised at
232 * @param array $context Active symbol table point of error
233 * @param array $trace Backtrace at point of error (undocumented HHVM
235 * @return bool Always returns false
237 public static function handleFatalError(
238 $level = null, $message = null, $file = null, $line = null,
239 $context = null, $trace = null
241 // Free reserved memory so that we have space to process OOM
243 self
::$reservedMemory = null;
245 if ( $level === null ) {
246 // Called as a shutdown handler, get data from error_get_last()
247 if ( static::$handledFatalCallback ) {
248 // Already called once (probably as an error handler callback
249 // under HHVM) so don't log again.
253 $lastError = error_get_last();
254 if ( $lastError !== null ) {
255 $level = $lastError['type'];
256 $message = $lastError['message'];
257 $file = $lastError['file'];
258 $line = $lastError['line'];
265 if ( !in_array( $level, self
::$fatalErrorTypes ) ) {
266 // Only interested in fatal errors, others should have been
267 // handled by MWExceptionHandler::handleError
271 $msg = "[{exception_id}] PHP Fatal Error: {$message}";
273 // Look at message to see if this is a class not found failure
274 // HHVM: Class undefined: foo
275 // PHP5: Class 'foo' not found
276 if ( preg_match( "/Class (undefined: \w+|'\w+' not found)/", $msg ) ) {
277 // @codingStandardsIgnoreStart Generic.Files.LineLength.TooLong
281 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.
283 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.
285 // @codingStandardsIgnoreEnd
288 // We can't just create an exception and log it as it is likely that
289 // the interpreter has unwound the stack already. If that is true the
290 // stacktrace we would get would be functionally empty. If however we
291 // have been called as an error handler callback *and* HHVM is in use
292 // we will have been provided with a useful stacktrace that we can
294 $trace = $trace ?
: debug_backtrace();
295 $logger = LoggerFactory
::getInstance( 'fatal' );
296 $logger->error( $msg, [
297 'fatal_exception' => [
298 'class' => 'ErrorException',
299 'message' => "PHP Fatal Error: {$message}",
303 'trace' => static::redactTrace( $trace ),
305 'exception_id' => wfRandomString( 8 ),
306 'caught_by' => self
::CAUGHT_BY_HANDLER
309 // Remember call so we don't double process via HHVM's fatal
310 // notifications and the shutdown hook behavior
311 static::$handledFatalCallback = true;
316 * Generate a string representation of an exception's stack trace
318 * Like Exception::getTraceAsString, but replaces argument values with
319 * argument type or class name.
321 * @param Exception|Throwable $e
323 * @see prettyPrintTrace()
325 public static function getRedactedTraceAsString( $e ) {
326 return self
::prettyPrintTrace( self
::getRedactedTrace( $e ) );
330 * Generate a string representation of a stacktrace.
332 * @param array $trace
333 * @param string $pad Constant padding to add to each line of trace
337 public static function prettyPrintTrace( array $trace, $pad = '' ) {
341 foreach ( $trace as $level => $frame ) {
342 if ( isset( $frame['file'] ) && isset( $frame['line'] ) ) {
343 $text .= "{$pad}#{$level} {$frame['file']}({$frame['line']}): ";
345 // 'file' and 'line' are unset for calls via call_user_func
346 // (T57634) This matches behaviour of
347 // Exception::getTraceAsString to instead display "[internal
349 $text .= "{$pad}#{$level} [internal function]: ";
352 if ( isset( $frame['class'] ) && isset( $frame['type'] ) && isset( $frame['function'] ) ) {
353 $text .= $frame['class'] . $frame['type'] . $frame['function'];
354 } elseif ( isset( $frame['function'] ) ) {
355 $text .= $frame['function'];
357 $text .= 'NO_FUNCTION_GIVEN';
360 if ( isset( $frame['args'] ) ) {
361 $text .= '(' . implode( ', ', $frame['args'] ) . ")\n";
368 $text .= "{$pad}#{$level} {main}";
374 * Return a copy of an exception's backtrace as an array.
376 * Like Exception::getTrace, but replaces each element in each frame's
377 * argument array with the name of its class (if the element is an object)
378 * or its type (if the element is a PHP primitive).
381 * @param Exception|Throwable $e
384 public static function getRedactedTrace( $e ) {
385 return static::redactTrace( $e->getTrace() );
389 * Redact a stacktrace generated by Exception::getTrace(),
390 * debug_backtrace() or similar means. Replaces each element in each
391 * frame's argument array with the name of its class (if the element is an
392 * object) or its type (if the element is a PHP primitive).
395 * @param array $trace Stacktrace
396 * @return array Stacktrace with arugment values converted to data types
398 public static function redactTrace( array $trace ) {
399 return array_map( function ( $frame ) {
400 if ( isset( $frame['args'] ) ) {
401 $frame['args'] = array_map( function ( $arg ) {
402 return is_object( $arg ) ?
get_class( $arg ) : gettype( $arg );
410 * Get the ID for this exception.
412 * The ID is saved so that one can match the one output to the user (when
413 * $wgShowExceptionDetails is set to false), to the entry in the debug log.
416 * @deprecated since 1.27: Exception IDs are synonymous with request IDs.
417 * @param Exception|Throwable $e
420 public static function getLogId( $e ) {
421 wfDeprecated( __METHOD__
, '1.27' );
422 return WebRequest
::getRequestId();
426 * If the exception occurred in the course of responding to a request,
427 * returns the requested URL. Otherwise, returns false.
430 * @return string|false
432 public static function getURL() {
434 if ( !isset( $wgRequest ) ||
$wgRequest instanceof FauxRequest
) {
437 return $wgRequest->getRequestURL();
441 * Get a message formatting the exception message and its origin.
444 * @param Exception|Throwable $e
447 public static function getLogMessage( $e ) {
448 $id = WebRequest
::getRequestId();
449 $type = get_class( $e );
450 $file = $e->getFile();
451 $line = $e->getLine();
452 $message = $e->getMessage();
453 $url = self
::getURL() ?
: '[no req]';
455 return "[$id] $url $type from line $line of $file: $message";
459 * @param Exception|Throwable $e
462 public static function getPublicLogMessage( $e ) {
463 $reqId = WebRequest
::getRequestId();
464 $type = get_class( $e );
465 return '[' . $reqId . '] '
466 . gmdate( 'Y-m-d H:i:s' ) . ': '
467 . 'Fatal exception of type "' . $type . '"';
471 * Get a PSR-3 log event context from an Exception.
473 * Creates a structured array containing information about the provided
474 * exception that can be used to augment a log message sent to a PSR-3
477 * @param Exception|Throwable $e
478 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
481 public static function getLogContext( $e, $catcher = self
::CAUGHT_BY_OTHER
) {
484 'exception_id' => WebRequest
::getRequestId(),
485 'caught_by' => $catcher
490 * Get a structured representation of an Exception.
492 * Returns an array of structured data (class, message, code, file,
493 * backtrace) derived from the given exception. The backtrace information
494 * will be redacted as per getRedactedTraceAsArray().
496 * @param Exception|Throwable $e
497 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
501 public static function getStructuredExceptionData( $e, $catcher = self
::CAUGHT_BY_OTHER
) {
502 global $wgLogExceptionBacktrace;
505 'id' => WebRequest
::getRequestId(),
506 'type' => get_class( $e ),
507 'file' => $e->getFile(),
508 'line' => $e->getLine(),
509 'message' => $e->getMessage(),
510 'code' => $e->getCode(),
511 'url' => self
::getURL() ?
: null,
512 'caught_by' => $catcher
515 if ( $e instanceof ErrorException
&&
516 ( error_reporting() & $e->getSeverity() ) === 0
518 // Flag surpressed errors
519 $data['suppressed'] = true;
522 if ( $wgLogExceptionBacktrace ) {
523 $data['backtrace'] = self
::getRedactedTrace( $e );
526 $previous = $e->getPrevious();
527 if ( $previous !== null ) {
528 $data['previous'] = self
::getStructuredExceptionData( $previous, $catcher );
535 * Serialize an Exception object to JSON.
537 * The JSON object will have keys 'id', 'file', 'line', 'message', and
538 * 'url'. These keys map to string values, with the exception of 'line',
539 * which is a number, and 'url', which may be either a string URL or or
540 * null if the exception did not occur in the context of serving a web
543 * If $wgLogExceptionBacktrace is true, it will also have a 'backtrace'
544 * key, mapped to the array return value of Exception::getTrace, but with
545 * each element in each frame's "args" array (if set) replaced with the
546 * argument's class name (if the argument is an object) or type name (if
547 * the argument is a PHP primitive).
549 * @par Sample JSON record ($wgLogExceptionBacktrace = false):
553 * "type": "MWException",
554 * "file": "/var/www/mediawiki/includes/cache/MessageCache.php",
556 * "message": "Non-string key given",
557 * "url": "/wiki/Main_Page"
561 * @par Sample JSON record ($wgLogExceptionBacktrace = true):
565 * "type": "MWException",
566 * "file": "/vagrant/mediawiki/includes/cache/MessageCache.php",
568 * "message": "Non-string key given",
569 * "url": "/wiki/Main_Page",
571 * "file": "/vagrant/mediawiki/extensions/VisualEditor/VisualEditor.hooks.php",
574 * "class": "MessageCache",
582 * @param Exception|Throwable $e
583 * @param bool $pretty Add non-significant whitespace to improve readability (default: false).
584 * @param int $escaping Bitfield consisting of FormatJson::.*_OK class constants.
585 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
586 * @return string|false JSON string if successful; false upon failure
588 public static function jsonSerializeException(
589 $e, $pretty = false, $escaping = 0, $catcher = self
::CAUGHT_BY_OTHER
591 return FormatJson
::encode(
592 self
::getStructuredExceptionData( $e, $catcher ),
599 * Log an exception to the exception log (if enabled).
601 * This method must not assume the exception is an MWException,
602 * it is also used to handle PHP exceptions or exceptions from other libraries.
605 * @param Exception|Throwable $e
606 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
608 public static function logException( $e, $catcher = self
::CAUGHT_BY_OTHER
) {
609 if ( !( $e instanceof MWException
) ||
$e->isLoggable() ) {
610 $logger = LoggerFactory
::getInstance( 'exception' );
612 self
::getLogMessage( $e ),
613 self
::getLogContext( $e, $catcher )
616 $json = self
::jsonSerializeException( $e, false, FormatJson
::ALL_OK
, $catcher );
617 if ( $json !== false ) {
618 $logger = LoggerFactory
::getInstance( 'exception-json' );
619 $logger->error( $json, [ 'private' => true ] );
622 Hooks
::run( 'LogException', [ $e, false ] );
627 * Log an exception that wasn't thrown but made to wrap an error.
630 * @param ErrorException $e
631 * @param string $channel
632 * @param string $level
634 protected static function logError(
635 ErrorException
$e, $channel, $level = LogLevel
::ERROR
637 $catcher = self
::CAUGHT_BY_HANDLER
;
638 // The set_error_handler callback is independent from error_reporting.
639 // Filter out unwanted errors manually (e.g. when
640 // MediaWiki\suppressWarnings is active).
641 $suppressed = ( error_reporting() & $e->getSeverity() ) === 0;
642 if ( !$suppressed ) {
643 $logger = LoggerFactory
::getInstance( $channel );
646 self
::getLogMessage( $e ),
647 self
::getLogContext( $e, $catcher )
651 // Include all errors in the json log (surpressed errors will be flagged)
652 $json = self
::jsonSerializeException( $e, false, FormatJson
::ALL_OK
, $catcher );
653 if ( $json !== false ) {
654 $logger = LoggerFactory
::getInstance( "{$channel}-json" );
655 $logger->log( $level, $json, [ 'private' => true ] );
658 Hooks
::run( 'LogException', [ $e, $suppressed ] );