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 ) {
63 global $wgShowExceptionDetails;
65 $cmdLine = MWException
::isCommandLine();
67 if ( $e instanceof MWException
) {
69 // Try and show the exception prettily, with the normal skin infrastructure
71 } catch ( Exception
$e2 ) {
72 // Exception occurred from within exception handler
73 // Show a simpler message for the original exception,
74 // don't try to invoke report()
75 $message = "MediaWiki internal error.\n\n";
77 if ( $wgShowExceptionDetails ) {
78 $message .= 'Original exception: ' . self
::getLogMessage( $e ) .
79 "\nBacktrace:\n" . self
::getRedactedTraceAsString( $e ) .
80 "\n\nException caught inside exception handler: " . self
::getLogMessage( $e2 ) .
81 "\nBacktrace:\n" . self
::getRedactedTraceAsString( $e2 );
83 $message .= "Exception caught inside exception handler.\n\n" .
84 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
85 "to show detailed debugging information.";
91 self
::printError( $message );
93 echo nl2br( htmlspecialchars( $message ) ) . "\n";
97 if ( !$wgShowExceptionDetails ) {
98 $message = self
::getPublicLogMessage( $e );
100 $message = self
::getLogMessage( $e ) .
102 self
::getRedactedTraceAsString( $e ) . "\n";
106 self
::printError( $message );
108 echo nl2br( htmlspecialchars( $message ) ) . "\n";
115 * Print a message, if possible to STDERR.
116 * Use this in command line mode only (see isCommandLine)
118 * @param string $message Failure text
120 public static function printError( $message ) {
121 # NOTE: STDERR may not be available, especially if php-cgi is used from the
122 # command line (bug #15602). Try to produce meaningful output anyway. Using
123 # echo may corrupt output to STDOUT though.
124 if ( defined( 'STDERR' ) ) {
125 fwrite( STDERR
, $message );
132 * If there are any open database transactions, roll them back and log
133 * the stack trace of the exception that should have been caught so the
134 * transaction could be aborted properly.
137 * @param Exception|Throwable $e
139 public static function rollbackMasterChangesAndLog( $e ) {
140 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
141 if ( $lbFactory->hasMasterChanges() ) {
142 $logger = LoggerFactory
::getInstance( 'Bug56269' );
144 'Exception thrown with an uncommited database transaction: ' .
145 self
::getLogMessage( $e ),
146 self
::getLogContext( $e )
149 $lbFactory->rollbackMasterChanges( __METHOD__
);
153 * Exception handler which simulates the appropriate catch() handling:
157 * } catch ( Exception $e ) {
159 * } catch ( Exception $e ) {
160 * echo $e->__toString();
164 * @param Exception|Throwable $e
166 public static function handleException( $e ) {
168 // Rollback DBs to avoid transaction notices. This may fail
169 // to rollback some DB due to connection issues or exceptions.
170 // However, any sane DB driver will rollback implicitly anyway.
171 self
::rollbackMasterChangesAndLog( $e );
172 } catch ( DBError
$e2 ) {
173 // If the DB is unreacheable, rollback() will throw an error
174 // and the error report() method might need messages from the DB,
175 // which would result in an exception loop. PHP may escalate such
176 // errors to "Exception thrown without a stack frame" fatals, but
177 // it's better to be explicit here.
178 self
::logException( $e2 );
181 self
::logException( $e );
184 // Exit value should be nonzero for the benefit of shell jobs
189 * Handler for set_error_handler() callback notifications.
191 * Receive a callback from the interpreter for a raised error, create an
192 * ErrorException, and log the exception to the 'error' logging
193 * channel(s). If the raised error is a fatal error type (only under HHVM)
194 * delegate to handleFatalError() instead.
198 * @param int $level Error level raised
199 * @param string $message
200 * @param string $file
206 public static function handleError(
207 $level, $message, $file = null, $line = null
209 if ( in_array( $level, self
::$fatalErrorTypes ) ) {
210 return call_user_func_array(
211 'MWExceptionHandler::handleFatalError', func_get_args()
215 // Map error constant to error name (reverse-engineer PHP error
218 case E_RECOVERABLE_ERROR
:
219 $levelName = 'Error';
223 case E_COMPILE_WARNING
:
225 $levelName = 'Warning';
229 $levelName = 'Notice';
232 $levelName = 'Strict Standards';
235 case E_USER_DEPRECATED
:
236 $levelName = 'Deprecated';
239 $levelName = 'Unknown error';
243 $e = new ErrorException( "PHP $levelName: $message", 0, $level, $file, $line );
244 self
::logError( $e, 'error' );
246 // This handler is for logging only. Return false will instruct PHP
247 // to continue regular handling.
252 * Dual purpose callback used as both a set_error_handler() callback and
253 * a registered shutdown function. Receive a callback from the interpreter
254 * for a raised error or system shutdown, check for a fatal error, and log
255 * to the 'fatal' logging channel.
257 * Special handling is included for missing class errors as they may
258 * indicate that the user needs to install 3rd-party libraries via
259 * Composer or other means.
263 * @param int $level Error level raised
264 * @param string $message Error message
265 * @param string $file File that error was raised in
266 * @param int $line Line number error was raised at
267 * @param array $context Active symbol table point of error
268 * @param array $trace Backtrace at point of error (undocumented HHVM
270 * @return bool Always returns false
272 public static function handleFatalError(
273 $level = null, $message = null, $file = null, $line = null,
274 $context = null, $trace = null
276 // Free reserved memory so that we have space to process OOM
278 self
::$reservedMemory = null;
280 if ( $level === null ) {
281 // Called as a shutdown handler, get data from error_get_last()
282 if ( static::$handledFatalCallback ) {
283 // Already called once (probably as an error handler callback
284 // under HHVM) so don't log again.
288 $lastError = error_get_last();
289 if ( $lastError !== null ) {
290 $level = $lastError['type'];
291 $message = $lastError['message'];
292 $file = $lastError['file'];
293 $line = $lastError['line'];
300 if ( !in_array( $level, self
::$fatalErrorTypes ) ) {
301 // Only interested in fatal errors, others should have been
302 // handled by MWExceptionHandler::handleError
306 $msg = "[{exception_id}] PHP Fatal Error: {$message}";
308 // Look at message to see if this is a class not found failure
309 // HHVM: Class undefined: foo
310 // PHP5: Class 'foo' not found
311 if ( preg_match( "/Class (undefined: \w+|'\w+' not found)/", $msg ) ) {
312 // @codingStandardsIgnoreStart Generic.Files.LineLength.TooLong
316 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.
318 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.
320 // @codingStandardsIgnoreEnd
323 // We can't just create an exception and log it as it is likely that
324 // the interpreter has unwound the stack already. If that is true the
325 // stacktrace we would get would be functionally empty. If however we
326 // have been called as an error handler callback *and* HHVM is in use
327 // we will have been provided with a useful stacktrace that we can
329 $trace = $trace ?
: debug_backtrace();
330 $logger = LoggerFactory
::getInstance( 'fatal' );
331 $logger->error( $msg, [
333 'class' => 'ErrorException',
334 'message' => "PHP Fatal Error: {$message}",
338 'trace' => static::redactTrace( $trace ),
340 'exception_id' => wfRandomString( 8 ),
343 // Remember call so we don't double process via HHVM's fatal
344 // notifications and the shutdown hook behavior
345 static::$handledFatalCallback = true;
350 * Generate a string representation of an exception's stack trace
352 * Like Exception::getTraceAsString, but replaces argument values with
353 * argument type or class name.
355 * @param Exception|Throwable $e
357 * @see prettyPrintTrace()
359 public static function getRedactedTraceAsString( $e ) {
360 return self
::prettyPrintTrace( self
::getRedactedTrace( $e ) );
364 * Generate a string representation of a stacktrace.
366 * @param array $trace
367 * @param string $pad Constant padding to add to each line of trace
371 public static function prettyPrintTrace( array $trace, $pad = '' ) {
375 foreach ( $trace as $level => $frame ) {
376 if ( isset( $frame['file'] ) && isset( $frame['line'] ) ) {
377 $text .= "{$pad}#{$level} {$frame['file']}({$frame['line']}): ";
379 // 'file' and 'line' are unset for calls via call_user_func
380 // (bug 55634) This matches behaviour of
381 // Exception::getTraceAsString to instead display "[internal
383 $text .= "{$pad}#{$level} [internal function]: ";
386 if ( isset( $frame['class'] ) && isset( $frame['type'] ) && isset( $frame['function'] ) ) {
387 $text .= $frame['class'] . $frame['type'] . $frame['function'];
388 } elseif ( isset( $frame['function'] ) ) {
389 $text .= $frame['function'];
391 $text .= 'NO_FUNCTION_GIVEN';
394 if ( isset( $frame['args'] ) ) {
395 $text .= '(' . implode( ', ', $frame['args'] ) . ")\n";
402 $text .= "{$pad}#{$level} {main}";
408 * Return a copy of an exception's backtrace as an array.
410 * Like Exception::getTrace, but replaces each element in each frame's
411 * argument array with the name of its class (if the element is an object)
412 * or its type (if the element is a PHP primitive).
415 * @param Exception|Throwable $e
418 public static function getRedactedTrace( $e ) {
419 return static::redactTrace( $e->getTrace() );
423 * Redact a stacktrace generated by Exception::getTrace(),
424 * debug_backtrace() or similar means. Replaces each element in each
425 * frame's argument array with the name of its class (if the element is an
426 * object) or its type (if the element is a PHP primitive).
429 * @param array $trace Stacktrace
430 * @return array Stacktrace with arugment values converted to data types
432 public static function redactTrace( array $trace ) {
433 return array_map( function ( $frame ) {
434 if ( isset( $frame['args'] ) ) {
435 $frame['args'] = array_map( function ( $arg ) {
436 return is_object( $arg ) ?
get_class( $arg ) : gettype( $arg );
444 * Get the ID for this exception.
446 * The ID is saved so that one can match the one output to the user (when
447 * $wgShowExceptionDetails is set to false), to the entry in the debug log.
450 * @deprecated since 1.27: Exception IDs are synonymous with request IDs.
451 * @param Exception|Throwable $e
454 public static function getLogId( $e ) {
455 wfDeprecated( __METHOD__
, '1.27' );
456 return WebRequest
::getRequestId();
460 * If the exception occurred in the course of responding to a request,
461 * returns the requested URL. Otherwise, returns false.
464 * @return string|false
466 public static function getURL() {
468 if ( !isset( $wgRequest ) ||
$wgRequest instanceof FauxRequest
) {
471 return $wgRequest->getRequestURL();
475 * Get a message formatting the exception message and its origin.
478 * @param Exception|Throwable $e
481 public static function getLogMessage( $e ) {
482 $id = WebRequest
::getRequestId();
483 $type = get_class( $e );
484 $file = $e->getFile();
485 $line = $e->getLine();
486 $message = $e->getMessage();
487 $url = self
::getURL() ?
: '[no req]';
489 return "[$id] $url $type from line $line of $file: $message";
493 * @param Exception|Throwable $e
496 public static function getPublicLogMessage( $e ) {
497 $reqId = WebRequest
::getRequestId();
498 $type = get_class( $e );
499 return '[' . $reqId . '] '
500 . gmdate( 'Y-m-d H:i:s' ) . ': '
501 . 'Fatal exception of type "' . $type . '"';
505 * Get a PSR-3 log event context from an Exception.
507 * Creates a structured array containing information about the provided
508 * exception that can be used to augment a log message sent to a PSR-3
511 * @param Exception|Throwable $e
514 public static function getLogContext( $e ) {
517 'exception_id' => WebRequest
::getRequestId(),
522 * Get a structured representation of an Exception.
524 * Returns an array of structured data (class, message, code, file,
525 * backtrace) derived from the given exception. The backtrace information
526 * will be redacted as per getRedactedTraceAsArray().
528 * @param Exception|Throwable $e
532 public static function getStructuredExceptionData( $e ) {
533 global $wgLogExceptionBacktrace;
535 'id' => WebRequest
::getRequestId(),
536 'type' => get_class( $e ),
537 'file' => $e->getFile(),
538 'line' => $e->getLine(),
539 'message' => $e->getMessage(),
540 'code' => $e->getCode(),
541 'url' => self
::getURL() ?
: null,
544 if ( $e instanceof ErrorException
&&
545 ( error_reporting() & $e->getSeverity() ) === 0
547 // Flag surpressed errors
548 $data['suppressed'] = true;
551 if ( $wgLogExceptionBacktrace ) {
552 $data['backtrace'] = self
::getRedactedTrace( $e );
555 $previous = $e->getPrevious();
556 if ( $previous !== null ) {
557 $data['previous'] = self
::getStructuredExceptionData( $previous );
564 * Serialize an Exception object to JSON.
566 * The JSON object will have keys 'id', 'file', 'line', 'message', and
567 * 'url'. These keys map to string values, with the exception of 'line',
568 * which is a number, and 'url', which may be either a string URL or or
569 * null if the exception did not occur in the context of serving a web
572 * If $wgLogExceptionBacktrace is true, it will also have a 'backtrace'
573 * key, mapped to the array return value of Exception::getTrace, but with
574 * each element in each frame's "args" array (if set) replaced with the
575 * argument's class name (if the argument is an object) or type name (if
576 * the argument is a PHP primitive).
578 * @par Sample JSON record ($wgLogExceptionBacktrace = false):
582 * "type": "MWException",
583 * "file": "/var/www/mediawiki/includes/cache/MessageCache.php",
585 * "message": "Non-string key given",
586 * "url": "/wiki/Main_Page"
590 * @par Sample JSON record ($wgLogExceptionBacktrace = true):
594 * "type": "MWException",
595 * "file": "/vagrant/mediawiki/includes/cache/MessageCache.php",
597 * "message": "Non-string key given",
598 * "url": "/wiki/Main_Page",
600 * "file": "/vagrant/mediawiki/extensions/VisualEditor/VisualEditor.hooks.php",
603 * "class": "MessageCache",
611 * @param Exception|Throwable $e
612 * @param bool $pretty Add non-significant whitespace to improve readability (default: false).
613 * @param int $escaping Bitfield consisting of FormatJson::.*_OK class constants.
614 * @return string|false JSON string if successful; false upon failure
616 public static function jsonSerializeException( $e, $pretty = false, $escaping = 0 ) {
617 $data = self
::getStructuredExceptionData( $e );
618 return FormatJson
::encode( $data, $pretty, $escaping );
622 * Log an exception to the exception log (if enabled).
624 * This method must not assume the exception is an MWException,
625 * it is also used to handle PHP exceptions or exceptions from other libraries.
628 * @param Exception|Throwable $e
630 public static function logException( $e ) {
631 if ( !( $e instanceof MWException
) ||
$e->isLoggable() ) {
632 $logger = LoggerFactory
::getInstance( 'exception' );
634 self
::getLogMessage( $e ),
635 self
::getLogContext( $e )
638 $json = self
::jsonSerializeException( $e, false, FormatJson
::ALL_OK
);
639 if ( $json !== false ) {
640 $logger = LoggerFactory
::getInstance( 'exception-json' );
641 $logger->error( $json, [ 'private' => true ] );
644 Hooks
::run( 'LogException', [ $e, false ] );
649 * Log an exception that wasn't thrown but made to wrap an error.
652 * @param ErrorException $e
653 * @param string $channel
655 protected static function logError( ErrorException
$e, $channel ) {
656 // The set_error_handler callback is independent from error_reporting.
657 // Filter out unwanted errors manually (e.g. when
658 // MediaWiki\suppressWarnings is active).
659 $suppressed = ( error_reporting() & $e->getSeverity() ) === 0;
660 if ( !$suppressed ) {
661 $logger = LoggerFactory
::getInstance( $channel );
663 self
::getLogMessage( $e ),
664 self
::getLogContext( $e )
668 // Include all errors in the json log (surpressed errors will be flagged)
669 $json = self
::jsonSerializeException( $e, false, FormatJson
::ALL_OK
);
670 if ( $json !== false ) {
671 $logger = LoggerFactory
::getInstance( "{$channel}-json" );
672 $logger->error( $json, [ 'private' => true ] );
675 Hooks
::run( 'LogException', [ $e, $suppressed ] );