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 MWExceptionRenderer
::output( $e, MWExceptionRenderer
::AS_PRETTY
);
66 } catch ( Exception
$e2 ) {
67 // Exception occurred from within exception handler
68 // Show a simpler message for the original exception,
69 // don't try to invoke report()
70 MWExceptionRenderer
::output( $e, MWExceptionRenderer
::AS_PRETTY
, $e2 );
75 * If there are any open database transactions, roll them back and log
76 * the stack trace of the exception that should have been caught so the
77 * transaction could be aborted properly.
80 * @param Exception|Throwable $e
82 public static function rollbackMasterChangesAndLog( $e ) {
83 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
84 if ( $lbFactory->hasMasterChanges() ) {
85 $logger = LoggerFactory
::getInstance( 'Bug56269' );
87 'Exception thrown with an uncommited database transaction: ' .
88 self
::getLogMessage( $e ),
89 self
::getLogContext( $e )
92 $lbFactory->rollbackMasterChanges( __METHOD__
);
96 * Exception handler which simulates the appropriate catch() handling:
100 * } catch ( Exception $e ) {
102 * } catch ( Exception $e ) {
103 * echo $e->__toString();
107 * @param Exception|Throwable $e
109 public static function handleException( $e ) {
111 // Rollback DBs to avoid transaction notices. This may fail
112 // to rollback some DB due to connection issues or exceptions.
113 // However, any sane DB driver will rollback implicitly anyway.
114 self
::rollbackMasterChangesAndLog( $e );
115 } catch ( DBError
$e2 ) {
116 // If the DB is unreacheable, rollback() will throw an error
117 // and the error report() method might need messages from the DB,
118 // which would result in an exception loop. PHP may escalate such
119 // errors to "Exception thrown without a stack frame" fatals, but
120 // it's better to be explicit here.
121 self
::logException( $e2 );
124 self
::logException( $e );
127 // Exit value should be nonzero for the benefit of shell jobs
132 * Handler for set_error_handler() callback notifications.
134 * Receive a callback from the interpreter for a raised error, create an
135 * ErrorException, and log the exception to the 'error' logging
136 * channel(s). If the raised error is a fatal error type (only under HHVM)
137 * delegate to handleFatalError() instead.
141 * @param int $level Error level raised
142 * @param string $message
143 * @param string $file
149 public static function handleError(
150 $level, $message, $file = null, $line = null
152 if ( in_array( $level, self
::$fatalErrorTypes ) ) {
153 return call_user_func_array(
154 'MWExceptionHandler::handleFatalError', func_get_args()
158 // Map error constant to error name (reverse-engineer PHP error
161 case E_RECOVERABLE_ERROR
:
162 $levelName = 'Error';
166 case E_COMPILE_WARNING
:
168 $levelName = 'Warning';
172 $levelName = 'Notice';
175 $levelName = 'Strict Standards';
178 case E_USER_DEPRECATED
:
179 $levelName = 'Deprecated';
182 $levelName = 'Unknown error';
186 $e = new ErrorException( "PHP $levelName: $message", 0, $level, $file, $line );
187 self
::logError( $e, 'error' );
189 // This handler is for logging only. Return false will instruct PHP
190 // to continue regular handling.
195 * Dual purpose callback used as both a set_error_handler() callback and
196 * a registered shutdown function. Receive a callback from the interpreter
197 * for a raised error or system shutdown, check for a fatal error, and log
198 * to the 'fatal' logging channel.
200 * Special handling is included for missing class errors as they may
201 * indicate that the user needs to install 3rd-party libraries via
202 * Composer or other means.
206 * @param int $level Error level raised
207 * @param string $message Error message
208 * @param string $file File that error was raised in
209 * @param int $line Line number error was raised at
210 * @param array $context Active symbol table point of error
211 * @param array $trace Backtrace at point of error (undocumented HHVM
213 * @return bool Always returns false
215 public static function handleFatalError(
216 $level = null, $message = null, $file = null, $line = null,
217 $context = null, $trace = null
219 // Free reserved memory so that we have space to process OOM
221 self
::$reservedMemory = null;
223 if ( $level === null ) {
224 // Called as a shutdown handler, get data from error_get_last()
225 if ( static::$handledFatalCallback ) {
226 // Already called once (probably as an error handler callback
227 // under HHVM) so don't log again.
231 $lastError = error_get_last();
232 if ( $lastError !== null ) {
233 $level = $lastError['type'];
234 $message = $lastError['message'];
235 $file = $lastError['file'];
236 $line = $lastError['line'];
243 if ( !in_array( $level, self
::$fatalErrorTypes ) ) {
244 // Only interested in fatal errors, others should have been
245 // handled by MWExceptionHandler::handleError
249 $msg = "[{exception_id}] PHP Fatal Error: {$message}";
251 // Look at message to see if this is a class not found failure
252 // HHVM: Class undefined: foo
253 // PHP5: Class 'foo' not found
254 if ( preg_match( "/Class (undefined: \w+|'\w+' not found)/", $msg ) ) {
255 // @codingStandardsIgnoreStart Generic.Files.LineLength.TooLong
259 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.
261 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.
263 // @codingStandardsIgnoreEnd
266 // We can't just create an exception and log it as it is likely that
267 // the interpreter has unwound the stack already. If that is true the
268 // stacktrace we would get would be functionally empty. If however we
269 // have been called as an error handler callback *and* HHVM is in use
270 // we will have been provided with a useful stacktrace that we can
272 $trace = $trace ?
: debug_backtrace();
273 $logger = LoggerFactory
::getInstance( 'fatal' );
274 $logger->error( $msg, [
276 'class' => 'ErrorException',
277 'message' => "PHP Fatal Error: {$message}",
281 'trace' => static::redactTrace( $trace ),
283 'exception_id' => wfRandomString( 8 ),
286 // Remember call so we don't double process via HHVM's fatal
287 // notifications and the shutdown hook behavior
288 static::$handledFatalCallback = true;
293 * Generate a string representation of an exception's stack trace
295 * Like Exception::getTraceAsString, but replaces argument values with
296 * argument type or class name.
298 * @param Exception|Throwable $e
300 * @see prettyPrintTrace()
302 public static function getRedactedTraceAsString( $e ) {
303 return self
::prettyPrintTrace( self
::getRedactedTrace( $e ) );
307 * Generate a string representation of a stacktrace.
309 * @param array $trace
310 * @param string $pad Constant padding to add to each line of trace
314 public static function prettyPrintTrace( array $trace, $pad = '' ) {
318 foreach ( $trace as $level => $frame ) {
319 if ( isset( $frame['file'] ) && isset( $frame['line'] ) ) {
320 $text .= "{$pad}#{$level} {$frame['file']}({$frame['line']}): ";
322 // 'file' and 'line' are unset for calls via call_user_func
323 // (bug 55634) This matches behaviour of
324 // Exception::getTraceAsString to instead display "[internal
326 $text .= "{$pad}#{$level} [internal function]: ";
329 if ( isset( $frame['class'] ) && isset( $frame['type'] ) && isset( $frame['function'] ) ) {
330 $text .= $frame['class'] . $frame['type'] . $frame['function'];
331 } elseif ( isset( $frame['function'] ) ) {
332 $text .= $frame['function'];
334 $text .= 'NO_FUNCTION_GIVEN';
337 if ( isset( $frame['args'] ) ) {
338 $text .= '(' . implode( ', ', $frame['args'] ) . ")\n";
345 $text .= "{$pad}#{$level} {main}";
351 * Return a copy of an exception's backtrace as an array.
353 * Like Exception::getTrace, but replaces each element in each frame's
354 * argument array with the name of its class (if the element is an object)
355 * or its type (if the element is a PHP primitive).
358 * @param Exception|Throwable $e
361 public static function getRedactedTrace( $e ) {
362 return static::redactTrace( $e->getTrace() );
366 * Redact a stacktrace generated by Exception::getTrace(),
367 * debug_backtrace() or similar means. Replaces each element in each
368 * frame's argument array with the name of its class (if the element is an
369 * object) or its type (if the element is a PHP primitive).
372 * @param array $trace Stacktrace
373 * @return array Stacktrace with arugment values converted to data types
375 public static function redactTrace( array $trace ) {
376 return array_map( function ( $frame ) {
377 if ( isset( $frame['args'] ) ) {
378 $frame['args'] = array_map( function ( $arg ) {
379 return is_object( $arg ) ?
get_class( $arg ) : gettype( $arg );
387 * Get the ID for this exception.
389 * The ID is saved so that one can match the one output to the user (when
390 * $wgShowExceptionDetails is set to false), to the entry in the debug log.
393 * @deprecated since 1.27: Exception IDs are synonymous with request IDs.
394 * @param Exception|Throwable $e
397 public static function getLogId( $e ) {
398 wfDeprecated( __METHOD__
, '1.27' );
399 return WebRequest
::getRequestId();
403 * If the exception occurred in the course of responding to a request,
404 * returns the requested URL. Otherwise, returns false.
407 * @return string|false
409 public static function getURL() {
411 if ( !isset( $wgRequest ) ||
$wgRequest instanceof FauxRequest
) {
414 return $wgRequest->getRequestURL();
418 * Get a message formatting the exception message and its origin.
421 * @param Exception|Throwable $e
424 public static function getLogMessage( $e ) {
425 $id = WebRequest
::getRequestId();
426 $type = get_class( $e );
427 $file = $e->getFile();
428 $line = $e->getLine();
429 $message = $e->getMessage();
430 $url = self
::getURL() ?
: '[no req]';
432 return "[$id] $url $type from line $line of $file: $message";
436 * @param Exception|Throwable $e
439 public static function getPublicLogMessage( $e ) {
440 $reqId = WebRequest
::getRequestId();
441 $type = get_class( $e );
442 return '[' . $reqId . '] '
443 . gmdate( 'Y-m-d H:i:s' ) . ': '
444 . 'Fatal exception of type "' . $type . '"';
448 * Get a PSR-3 log event context from an Exception.
450 * Creates a structured array containing information about the provided
451 * exception that can be used to augment a log message sent to a PSR-3
454 * @param Exception|Throwable $e
457 public static function getLogContext( $e ) {
460 'exception_id' => WebRequest
::getRequestId(),
465 * Get a structured representation of an Exception.
467 * Returns an array of structured data (class, message, code, file,
468 * backtrace) derived from the given exception. The backtrace information
469 * will be redacted as per getRedactedTraceAsArray().
471 * @param Exception|Throwable $e
475 public static function getStructuredExceptionData( $e ) {
476 global $wgLogExceptionBacktrace;
478 'id' => WebRequest
::getRequestId(),
479 'type' => get_class( $e ),
480 'file' => $e->getFile(),
481 'line' => $e->getLine(),
482 'message' => $e->getMessage(),
483 'code' => $e->getCode(),
484 'url' => self
::getURL() ?
: null,
487 if ( $e instanceof ErrorException
&&
488 ( error_reporting() & $e->getSeverity() ) === 0
490 // Flag surpressed errors
491 $data['suppressed'] = true;
494 if ( $wgLogExceptionBacktrace ) {
495 $data['backtrace'] = self
::getRedactedTrace( $e );
498 $previous = $e->getPrevious();
499 if ( $previous !== null ) {
500 $data['previous'] = self
::getStructuredExceptionData( $previous );
507 * Serialize an Exception object to JSON.
509 * The JSON object will have keys 'id', 'file', 'line', 'message', and
510 * 'url'. These keys map to string values, with the exception of 'line',
511 * which is a number, and 'url', which may be either a string URL or or
512 * null if the exception did not occur in the context of serving a web
515 * If $wgLogExceptionBacktrace is true, it will also have a 'backtrace'
516 * key, mapped to the array return value of Exception::getTrace, but with
517 * each element in each frame's "args" array (if set) replaced with the
518 * argument's class name (if the argument is an object) or type name (if
519 * the argument is a PHP primitive).
521 * @par Sample JSON record ($wgLogExceptionBacktrace = false):
525 * "type": "MWException",
526 * "file": "/var/www/mediawiki/includes/cache/MessageCache.php",
528 * "message": "Non-string key given",
529 * "url": "/wiki/Main_Page"
533 * @par Sample JSON record ($wgLogExceptionBacktrace = true):
537 * "type": "MWException",
538 * "file": "/vagrant/mediawiki/includes/cache/MessageCache.php",
540 * "message": "Non-string key given",
541 * "url": "/wiki/Main_Page",
543 * "file": "/vagrant/mediawiki/extensions/VisualEditor/VisualEditor.hooks.php",
546 * "class": "MessageCache",
554 * @param Exception|Throwable $e
555 * @param bool $pretty Add non-significant whitespace to improve readability (default: false).
556 * @param int $escaping Bitfield consisting of FormatJson::.*_OK class constants.
557 * @return string|false JSON string if successful; false upon failure
559 public static function jsonSerializeException( $e, $pretty = false, $escaping = 0 ) {
560 $data = self
::getStructuredExceptionData( $e );
561 return FormatJson
::encode( $data, $pretty, $escaping );
565 * Log an exception to the exception log (if enabled).
567 * This method must not assume the exception is an MWException,
568 * it is also used to handle PHP exceptions or exceptions from other libraries.
571 * @param Exception|Throwable $e
573 public static function logException( $e ) {
574 if ( !( $e instanceof MWException
) ||
$e->isLoggable() ) {
575 $logger = LoggerFactory
::getInstance( 'exception' );
577 self
::getLogMessage( $e ),
578 self
::getLogContext( $e )
581 $json = self
::jsonSerializeException( $e, false, FormatJson
::ALL_OK
);
582 if ( $json !== false ) {
583 $logger = LoggerFactory
::getInstance( 'exception-json' );
584 $logger->error( $json, [ 'private' => true ] );
587 Hooks
::run( 'LogException', [ $e, false ] );
592 * Log an exception that wasn't thrown but made to wrap an error.
595 * @param ErrorException $e
596 * @param string $channel
598 protected static function logError( ErrorException
$e, $channel ) {
599 // The set_error_handler callback is independent from error_reporting.
600 // Filter out unwanted errors manually (e.g. when
601 // MediaWiki\suppressWarnings is active).
602 $suppressed = ( error_reporting() & $e->getSeverity() ) === 0;
603 if ( !$suppressed ) {
604 $logger = LoggerFactory
::getInstance( $channel );
606 self
::getLogMessage( $e ),
607 self
::getLogContext( $e )
611 // Include all errors in the json log (surpressed errors will be flagged)
612 $json = self
::jsonSerializeException( $e, false, FormatJson
::ALL_OK
);
613 if ( $json !== false ) {
614 $logger = LoggerFactory
::getInstance( "{$channel}-json" );
615 $logger->error( $json, [ 'private' => true ] );
618 Hooks
::run( 'LogException', [ $e, $suppressed ] );