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
;
25 * Handler class for MWExceptions
28 class MWExceptionHandler
{
31 * @var string $reservedMemory
33 protected static $reservedMemory;
35 * @var array $fatalErrorTypes
37 protected static $fatalErrorTypes = [
38 E_ERROR
, E_PARSE
, E_CORE_ERROR
, E_COMPILE_ERROR
, E_USER_ERROR
,
39 /* HHVM's FATAL_ERROR level */ 16777217,
42 * @var bool $handledFatalCallback
44 protected static $handledFatalCallback = false;
47 * Install handlers with PHP.
49 public static function installHandler() {
50 set_exception_handler( 'MWExceptionHandler::handleException' );
51 set_error_handler( 'MWExceptionHandler::handleError' );
53 // Reserve 16k of memory so we can report OOM fatals
54 self
::$reservedMemory = str_repeat( ' ', 16384 );
55 register_shutdown_function( 'MWExceptionHandler::handleFatalError' );
59 * Report an exception to the user
60 * @param Exception|Throwable $e
62 protected static function report( $e ) {
64 // Try and show the exception prettily, with the normal skin infrastructure
65 if ( $e instanceof MWException
) {
66 // Delegate to MWException until all subclasses are handled by
67 // MWExceptionRenderer and MWException::report() has been
71 MWExceptionRenderer
::output( $e, MWExceptionRenderer
::AS_PRETTY
);
73 } catch ( Exception
$e2 ) {
74 // Exception occurred from within exception handler
75 // Show a simpler message for the original exception,
76 // don't try to invoke report()
77 MWExceptionRenderer
::output( $e, MWExceptionRenderer
::AS_RAW
, $e2 );
82 * If there are any open database transactions, roll them back and log
83 * the stack trace of the exception that should have been caught so the
84 * transaction could be aborted properly.
87 * @param Exception|Throwable $e
89 public static function rollbackMasterChangesAndLog( $e ) {
90 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
91 if ( $lbFactory->hasMasterChanges() ) {
92 $logger = LoggerFactory
::getInstance( 'Bug56269' );
94 'Exception thrown with an uncommited database transaction: ' .
95 self
::getLogMessage( $e ),
96 self
::getLogContext( $e )
99 $lbFactory->rollbackMasterChanges( __METHOD__
);
103 * Exception handler which simulates the appropriate catch() handling:
107 * } catch ( Exception $e ) {
109 * } catch ( Exception $e ) {
110 * echo $e->__toString();
114 * @param Exception|Throwable $e
116 public static function handleException( $e ) {
118 // Rollback DBs to avoid transaction notices. This may fail
119 // to rollback some DB due to connection issues or exceptions.
120 // However, any sane DB driver will rollback implicitly anyway.
121 self
::rollbackMasterChangesAndLog( $e );
122 } catch ( DBError
$e2 ) {
123 // If the DB is unreacheable, rollback() will throw an error
124 // and the error report() method might need messages from the DB,
125 // which would result in an exception loop. PHP may escalate such
126 // errors to "Exception thrown without a stack frame" fatals, but
127 // it's better to be explicit here.
128 self
::logException( $e2 );
131 self
::logException( $e );
134 // Exit value should be nonzero for the benefit of shell jobs
139 * Handler for set_error_handler() callback notifications.
141 * Receive a callback from the interpreter for a raised error, create an
142 * ErrorException, and log the exception to the 'error' logging
143 * channel(s). If the raised error is a fatal error type (only under HHVM)
144 * delegate to handleFatalError() instead.
148 * @param int $level Error level raised
149 * @param string $message
150 * @param string $file
156 public static function handleError(
157 $level, $message, $file = null, $line = null
159 if ( in_array( $level, self
::$fatalErrorTypes ) ) {
160 return call_user_func_array(
161 'MWExceptionHandler::handleFatalError', func_get_args()
165 // Map error constant to error name (reverse-engineer PHP error
168 case E_RECOVERABLE_ERROR
:
169 $levelName = 'Error';
173 case E_COMPILE_WARNING
:
175 $levelName = 'Warning';
179 $levelName = 'Notice';
182 $levelName = 'Strict Standards';
185 case E_USER_DEPRECATED
:
186 $levelName = 'Deprecated';
189 $levelName = 'Unknown error';
193 $e = new ErrorException( "PHP $levelName: $message", 0, $level, $file, $line );
194 self
::logError( $e, 'error' );
196 // This handler is for logging only. Return false will instruct PHP
197 // to continue regular handling.
202 * Dual purpose callback used as both a set_error_handler() callback and
203 * a registered shutdown function. Receive a callback from the interpreter
204 * for a raised error or system shutdown, check for a fatal error, and log
205 * to the 'fatal' logging channel.
207 * Special handling is included for missing class errors as they may
208 * indicate that the user needs to install 3rd-party libraries via
209 * Composer or other means.
213 * @param int $level Error level raised
214 * @param string $message Error message
215 * @param string $file File that error was raised in
216 * @param int $line Line number error was raised at
217 * @param array $context Active symbol table point of error
218 * @param array $trace Backtrace at point of error (undocumented HHVM
220 * @return bool Always returns false
222 public static function handleFatalError(
223 $level = null, $message = null, $file = null, $line = null,
224 $context = null, $trace = null
226 // Free reserved memory so that we have space to process OOM
228 self
::$reservedMemory = null;
230 if ( $level === null ) {
231 // Called as a shutdown handler, get data from error_get_last()
232 if ( static::$handledFatalCallback ) {
233 // Already called once (probably as an error handler callback
234 // under HHVM) so don't log again.
238 $lastError = error_get_last();
239 if ( $lastError !== null ) {
240 $level = $lastError['type'];
241 $message = $lastError['message'];
242 $file = $lastError['file'];
243 $line = $lastError['line'];
250 if ( !in_array( $level, self
::$fatalErrorTypes ) ) {
251 // Only interested in fatal errors, others should have been
252 // handled by MWExceptionHandler::handleError
256 $msg = "[{exception_id}] PHP Fatal Error: {$message}";
258 // Look at message to see if this is a class not found failure
259 // HHVM: Class undefined: foo
260 // PHP5: Class 'foo' not found
261 if ( preg_match( "/Class (undefined: \w+|'\w+' not found)/", $msg ) ) {
262 // @codingStandardsIgnoreStart Generic.Files.LineLength.TooLong
266 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.
268 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.
270 // @codingStandardsIgnoreEnd
273 // We can't just create an exception and log it as it is likely that
274 // the interpreter has unwound the stack already. If that is true the
275 // stacktrace we would get would be functionally empty. If however we
276 // have been called as an error handler callback *and* HHVM is in use
277 // we will have been provided with a useful stacktrace that we can
279 $trace = $trace ?
: debug_backtrace();
280 $logger = LoggerFactory
::getInstance( 'fatal' );
281 $logger->error( $msg, [
283 'class' => 'ErrorException',
284 'message' => "PHP Fatal Error: {$message}",
288 'trace' => static::redactTrace( $trace ),
290 'exception_id' => wfRandomString( 8 ),
293 // Remember call so we don't double process via HHVM's fatal
294 // notifications and the shutdown hook behavior
295 static::$handledFatalCallback = true;
300 * Generate a string representation of an exception's stack trace
302 * Like Exception::getTraceAsString, but replaces argument values with
303 * argument type or class name.
305 * @param Exception|Throwable $e
307 * @see prettyPrintTrace()
309 public static function getRedactedTraceAsString( $e ) {
310 return self
::prettyPrintTrace( self
::getRedactedTrace( $e ) );
314 * Generate a string representation of a stacktrace.
316 * @param array $trace
317 * @param string $pad Constant padding to add to each line of trace
321 public static function prettyPrintTrace( array $trace, $pad = '' ) {
325 foreach ( $trace as $level => $frame ) {
326 if ( isset( $frame['file'] ) && isset( $frame['line'] ) ) {
327 $text .= "{$pad}#{$level} {$frame['file']}({$frame['line']}): ";
329 // 'file' and 'line' are unset for calls via call_user_func
330 // (bug 55634) This matches behaviour of
331 // Exception::getTraceAsString to instead display "[internal
333 $text .= "{$pad}#{$level} [internal function]: ";
336 if ( isset( $frame['class'] ) && isset( $frame['type'] ) && isset( $frame['function'] ) ) {
337 $text .= $frame['class'] . $frame['type'] . $frame['function'];
338 } elseif ( isset( $frame['function'] ) ) {
339 $text .= $frame['function'];
341 $text .= 'NO_FUNCTION_GIVEN';
344 if ( isset( $frame['args'] ) ) {
345 $text .= '(' . implode( ', ', $frame['args'] ) . ")\n";
352 $text .= "{$pad}#{$level} {main}";
358 * Return a copy of an exception's backtrace as an array.
360 * Like Exception::getTrace, but replaces each element in each frame's
361 * argument array with the name of its class (if the element is an object)
362 * or its type (if the element is a PHP primitive).
365 * @param Exception|Throwable $e
368 public static function getRedactedTrace( $e ) {
369 return static::redactTrace( $e->getTrace() );
373 * Redact a stacktrace generated by Exception::getTrace(),
374 * debug_backtrace() or similar means. Replaces each element in each
375 * frame's argument array with the name of its class (if the element is an
376 * object) or its type (if the element is a PHP primitive).
379 * @param array $trace Stacktrace
380 * @return array Stacktrace with arugment values converted to data types
382 public static function redactTrace( array $trace ) {
383 return array_map( function ( $frame ) {
384 if ( isset( $frame['args'] ) ) {
385 $frame['args'] = array_map( function ( $arg ) {
386 return is_object( $arg ) ?
get_class( $arg ) : gettype( $arg );
394 * Get the ID for this exception.
396 * The ID is saved so that one can match the one output to the user (when
397 * $wgShowExceptionDetails is set to false), to the entry in the debug log.
400 * @deprecated since 1.27: Exception IDs are synonymous with request IDs.
401 * @param Exception|Throwable $e
404 public static function getLogId( $e ) {
405 wfDeprecated( __METHOD__
, '1.27' );
406 return WebRequest
::getRequestId();
410 * If the exception occurred in the course of responding to a request,
411 * returns the requested URL. Otherwise, returns false.
414 * @return string|false
416 public static function getURL() {
418 if ( !isset( $wgRequest ) ||
$wgRequest instanceof FauxRequest
) {
421 return $wgRequest->getRequestURL();
425 * Get a message formatting the exception message and its origin.
428 * @param Exception|Throwable $e
431 public static function getLogMessage( $e ) {
432 $id = WebRequest
::getRequestId();
433 $type = get_class( $e );
434 $file = $e->getFile();
435 $line = $e->getLine();
436 $message = $e->getMessage();
437 $url = self
::getURL() ?
: '[no req]';
439 return "[$id] $url $type from line $line of $file: $message";
443 * @param Exception|Throwable $e
446 public static function getPublicLogMessage( $e ) {
447 $reqId = WebRequest
::getRequestId();
448 $type = get_class( $e );
449 return '[' . $reqId . '] '
450 . gmdate( 'Y-m-d H:i:s' ) . ': '
451 . 'Fatal exception of type "' . $type . '"';
455 * Get a PSR-3 log event context from an Exception.
457 * Creates a structured array containing information about the provided
458 * exception that can be used to augment a log message sent to a PSR-3
461 * @param Exception|Throwable $e
464 public static function getLogContext( $e ) {
467 'exception_id' => WebRequest
::getRequestId(),
472 * Get a structured representation of an Exception.
474 * Returns an array of structured data (class, message, code, file,
475 * backtrace) derived from the given exception. The backtrace information
476 * will be redacted as per getRedactedTraceAsArray().
478 * @param Exception|Throwable $e
482 public static function getStructuredExceptionData( $e ) {
483 global $wgLogExceptionBacktrace;
485 'id' => WebRequest
::getRequestId(),
486 'type' => get_class( $e ),
487 'file' => $e->getFile(),
488 'line' => $e->getLine(),
489 'message' => $e->getMessage(),
490 'code' => $e->getCode(),
491 'url' => self
::getURL() ?
: null,
494 if ( $e instanceof ErrorException
&&
495 ( error_reporting() & $e->getSeverity() ) === 0
497 // Flag surpressed errors
498 $data['suppressed'] = true;
501 if ( $wgLogExceptionBacktrace ) {
502 $data['backtrace'] = self
::getRedactedTrace( $e );
505 $previous = $e->getPrevious();
506 if ( $previous !== null ) {
507 $data['previous'] = self
::getStructuredExceptionData( $previous );
514 * Serialize an Exception object to JSON.
516 * The JSON object will have keys 'id', 'file', 'line', 'message', and
517 * 'url'. These keys map to string values, with the exception of 'line',
518 * which is a number, and 'url', which may be either a string URL or or
519 * null if the exception did not occur in the context of serving a web
522 * If $wgLogExceptionBacktrace is true, it will also have a 'backtrace'
523 * key, mapped to the array return value of Exception::getTrace, but with
524 * each element in each frame's "args" array (if set) replaced with the
525 * argument's class name (if the argument is an object) or type name (if
526 * the argument is a PHP primitive).
528 * @par Sample JSON record ($wgLogExceptionBacktrace = false):
532 * "type": "MWException",
533 * "file": "/var/www/mediawiki/includes/cache/MessageCache.php",
535 * "message": "Non-string key given",
536 * "url": "/wiki/Main_Page"
540 * @par Sample JSON record ($wgLogExceptionBacktrace = true):
544 * "type": "MWException",
545 * "file": "/vagrant/mediawiki/includes/cache/MessageCache.php",
547 * "message": "Non-string key given",
548 * "url": "/wiki/Main_Page",
550 * "file": "/vagrant/mediawiki/extensions/VisualEditor/VisualEditor.hooks.php",
553 * "class": "MessageCache",
561 * @param Exception|Throwable $e
562 * @param bool $pretty Add non-significant whitespace to improve readability (default: false).
563 * @param int $escaping Bitfield consisting of FormatJson::.*_OK class constants.
564 * @return string|false JSON string if successful; false upon failure
566 public static function jsonSerializeException( $e, $pretty = false, $escaping = 0 ) {
567 $data = self
::getStructuredExceptionData( $e );
568 return FormatJson
::encode( $data, $pretty, $escaping );
572 * Log an exception to the exception log (if enabled).
574 * This method must not assume the exception is an MWException,
575 * it is also used to handle PHP exceptions or exceptions from other libraries.
578 * @param Exception|Throwable $e
580 public static function logException( $e ) {
581 if ( !( $e instanceof MWException
) ||
$e->isLoggable() ) {
582 $logger = LoggerFactory
::getInstance( 'exception' );
584 self
::getLogMessage( $e ),
585 self
::getLogContext( $e )
588 $json = self
::jsonSerializeException( $e, false, FormatJson
::ALL_OK
);
589 if ( $json !== false ) {
590 $logger = LoggerFactory
::getInstance( 'exception-json' );
591 $logger->error( $json, [ 'private' => true ] );
594 Hooks
::run( 'LogException', [ $e, false ] );
599 * Log an exception that wasn't thrown but made to wrap an error.
602 * @param ErrorException $e
603 * @param string $channel
605 protected static function logError( ErrorException
$e, $channel ) {
606 // The set_error_handler callback is independent from error_reporting.
607 // Filter out unwanted errors manually (e.g. when
608 // MediaWiki\suppressWarnings is active).
609 $suppressed = ( error_reporting() & $e->getSeverity() ) === 0;
610 if ( !$suppressed ) {
611 $logger = LoggerFactory
::getInstance( $channel );
613 self
::getLogMessage( $e ),
614 self
::getLogContext( $e )
618 // Include all errors in the json log (surpressed errors will be flagged)
619 $json = self
::jsonSerializeException( $e, false, FormatJson
::ALL_OK
);
620 if ( $json !== false ) {
621 $logger = LoggerFactory
::getInstance( "{$channel}-json" );
622 $logger->error( $json, [ 'private' => true ] );
625 Hooks
::run( 'LogException', [ $e, $suppressed ] );