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(
72 $e, MWExceptionRenderer
::AS_PRETTY
);
74 } catch ( Exception
$e2 ) {
75 // Exception occurred from within exception handler
76 // Show a simpler message for the original exception,
77 // don't try to invoke report()
78 MWExceptionRenderer
::output( $e, MWExceptionRenderer
::AS_PRETTY
, $e2 );
83 * If there are any open database transactions, roll them back and log
84 * the stack trace of the exception that should have been caught so the
85 * transaction could be aborted properly.
88 * @param Exception|Throwable $e
90 public static function rollbackMasterChangesAndLog( $e ) {
91 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
92 if ( $lbFactory->hasMasterChanges() ) {
93 $logger = LoggerFactory
::getInstance( 'Bug56269' );
95 'Exception thrown with an uncommited database transaction: ' .
96 self
::getLogMessage( $e ),
97 self
::getLogContext( $e )
100 $lbFactory->rollbackMasterChanges( __METHOD__
);
104 * Exception handler which simulates the appropriate catch() handling:
108 * } catch ( Exception $e ) {
110 * } catch ( Exception $e ) {
111 * echo $e->__toString();
115 * @param Exception|Throwable $e
117 public static function handleException( $e ) {
119 // Rollback DBs to avoid transaction notices. This may fail
120 // to rollback some DB due to connection issues or exceptions.
121 // However, any sane DB driver will rollback implicitly anyway.
122 self
::rollbackMasterChangesAndLog( $e );
123 } catch ( DBError
$e2 ) {
124 // If the DB is unreacheable, rollback() will throw an error
125 // and the error report() method might need messages from the DB,
126 // which would result in an exception loop. PHP may escalate such
127 // errors to "Exception thrown without a stack frame" fatals, but
128 // it's better to be explicit here.
129 self
::logException( $e2 );
132 self
::logException( $e );
135 // Exit value should be nonzero for the benefit of shell jobs
140 * Handler for set_error_handler() callback notifications.
142 * Receive a callback from the interpreter for a raised error, create an
143 * ErrorException, and log the exception to the 'error' logging
144 * channel(s). If the raised error is a fatal error type (only under HHVM)
145 * delegate to handleFatalError() instead.
149 * @param int $level Error level raised
150 * @param string $message
151 * @param string $file
157 public static function handleError(
158 $level, $message, $file = null, $line = null
160 if ( in_array( $level, self
::$fatalErrorTypes ) ) {
161 return call_user_func_array(
162 'MWExceptionHandler::handleFatalError', func_get_args()
166 // Map error constant to error name (reverse-engineer PHP error
169 case E_RECOVERABLE_ERROR
:
170 $levelName = 'Error';
174 case E_COMPILE_WARNING
:
176 $levelName = 'Warning';
180 $levelName = 'Notice';
183 $levelName = 'Strict Standards';
186 case E_USER_DEPRECATED
:
187 $levelName = 'Deprecated';
190 $levelName = 'Unknown error';
194 $e = new ErrorException( "PHP $levelName: $message", 0, $level, $file, $line );
195 self
::logError( $e, 'error' );
197 // This handler is for logging only. Return false will instruct PHP
198 // to continue regular handling.
203 * Dual purpose callback used as both a set_error_handler() callback and
204 * a registered shutdown function. Receive a callback from the interpreter
205 * for a raised error or system shutdown, check for a fatal error, and log
206 * to the 'fatal' logging channel.
208 * Special handling is included for missing class errors as they may
209 * indicate that the user needs to install 3rd-party libraries via
210 * Composer or other means.
214 * @param int $level Error level raised
215 * @param string $message Error message
216 * @param string $file File that error was raised in
217 * @param int $line Line number error was raised at
218 * @param array $context Active symbol table point of error
219 * @param array $trace Backtrace at point of error (undocumented HHVM
221 * @return bool Always returns false
223 public static function handleFatalError(
224 $level = null, $message = null, $file = null, $line = null,
225 $context = null, $trace = null
227 // Free reserved memory so that we have space to process OOM
229 self
::$reservedMemory = null;
231 if ( $level === null ) {
232 // Called as a shutdown handler, get data from error_get_last()
233 if ( static::$handledFatalCallback ) {
234 // Already called once (probably as an error handler callback
235 // under HHVM) so don't log again.
239 $lastError = error_get_last();
240 if ( $lastError !== null ) {
241 $level = $lastError['type'];
242 $message = $lastError['message'];
243 $file = $lastError['file'];
244 $line = $lastError['line'];
251 if ( !in_array( $level, self
::$fatalErrorTypes ) ) {
252 // Only interested in fatal errors, others should have been
253 // handled by MWExceptionHandler::handleError
257 $msg = "[{exception_id}] PHP Fatal Error: {$message}";
259 // Look at message to see if this is a class not found failure
260 // HHVM: Class undefined: foo
261 // PHP5: Class 'foo' not found
262 if ( preg_match( "/Class (undefined: \w+|'\w+' not found)/", $msg ) ) {
263 // @codingStandardsIgnoreStart Generic.Files.LineLength.TooLong
267 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.
269 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.
271 // @codingStandardsIgnoreEnd
274 // We can't just create an exception and log it as it is likely that
275 // the interpreter has unwound the stack already. If that is true the
276 // stacktrace we would get would be functionally empty. If however we
277 // have been called as an error handler callback *and* HHVM is in use
278 // we will have been provided with a useful stacktrace that we can
280 $trace = $trace ?
: debug_backtrace();
281 $logger = LoggerFactory
::getInstance( 'fatal' );
282 $logger->error( $msg, [
284 'class' => 'ErrorException',
285 'message' => "PHP Fatal Error: {$message}",
289 'trace' => static::redactTrace( $trace ),
291 'exception_id' => wfRandomString( 8 ),
294 // Remember call so we don't double process via HHVM's fatal
295 // notifications and the shutdown hook behavior
296 static::$handledFatalCallback = true;
301 * Generate a string representation of an exception's stack trace
303 * Like Exception::getTraceAsString, but replaces argument values with
304 * argument type or class name.
306 * @param Exception|Throwable $e
308 * @see prettyPrintTrace()
310 public static function getRedactedTraceAsString( $e ) {
311 return self
::prettyPrintTrace( self
::getRedactedTrace( $e ) );
315 * Generate a string representation of a stacktrace.
317 * @param array $trace
318 * @param string $pad Constant padding to add to each line of trace
322 public static function prettyPrintTrace( array $trace, $pad = '' ) {
326 foreach ( $trace as $level => $frame ) {
327 if ( isset( $frame['file'] ) && isset( $frame['line'] ) ) {
328 $text .= "{$pad}#{$level} {$frame['file']}({$frame['line']}): ";
330 // 'file' and 'line' are unset for calls via call_user_func
331 // (bug 55634) This matches behaviour of
332 // Exception::getTraceAsString to instead display "[internal
334 $text .= "{$pad}#{$level} [internal function]: ";
337 if ( isset( $frame['class'] ) && isset( $frame['type'] ) && isset( $frame['function'] ) ) {
338 $text .= $frame['class'] . $frame['type'] . $frame['function'];
339 } elseif ( isset( $frame['function'] ) ) {
340 $text .= $frame['function'];
342 $text .= 'NO_FUNCTION_GIVEN';
345 if ( isset( $frame['args'] ) ) {
346 $text .= '(' . implode( ', ', $frame['args'] ) . ")\n";
353 $text .= "{$pad}#{$level} {main}";
359 * Return a copy of an exception's backtrace as an array.
361 * Like Exception::getTrace, but replaces each element in each frame's
362 * argument array with the name of its class (if the element is an object)
363 * or its type (if the element is a PHP primitive).
366 * @param Exception|Throwable $e
369 public static function getRedactedTrace( $e ) {
370 return static::redactTrace( $e->getTrace() );
374 * Redact a stacktrace generated by Exception::getTrace(),
375 * debug_backtrace() or similar means. Replaces each element in each
376 * frame's argument array with the name of its class (if the element is an
377 * object) or its type (if the element is a PHP primitive).
380 * @param array $trace Stacktrace
381 * @return array Stacktrace with arugment values converted to data types
383 public static function redactTrace( array $trace ) {
384 return array_map( function ( $frame ) {
385 if ( isset( $frame['args'] ) ) {
386 $frame['args'] = array_map( function ( $arg ) {
387 return is_object( $arg ) ?
get_class( $arg ) : gettype( $arg );
395 * Get the ID for this exception.
397 * The ID is saved so that one can match the one output to the user (when
398 * $wgShowExceptionDetails is set to false), to the entry in the debug log.
401 * @deprecated since 1.27: Exception IDs are synonymous with request IDs.
402 * @param Exception|Throwable $e
405 public static function getLogId( $e ) {
406 wfDeprecated( __METHOD__
, '1.27' );
407 return WebRequest
::getRequestId();
411 * If the exception occurred in the course of responding to a request,
412 * returns the requested URL. Otherwise, returns false.
415 * @return string|false
417 public static function getURL() {
419 if ( !isset( $wgRequest ) ||
$wgRequest instanceof FauxRequest
) {
422 return $wgRequest->getRequestURL();
426 * Get a message formatting the exception message and its origin.
429 * @param Exception|Throwable $e
432 public static function getLogMessage( $e ) {
433 $id = WebRequest
::getRequestId();
434 $type = get_class( $e );
435 $file = $e->getFile();
436 $line = $e->getLine();
437 $message = $e->getMessage();
438 $url = self
::getURL() ?
: '[no req]';
440 return "[$id] $url $type from line $line of $file: $message";
444 * @param Exception|Throwable $e
447 public static function getPublicLogMessage( $e ) {
448 $reqId = WebRequest
::getRequestId();
449 $type = get_class( $e );
450 return '[' . $reqId . '] '
451 . gmdate( 'Y-m-d H:i:s' ) . ': '
452 . 'Fatal exception of type "' . $type . '"';
456 * Get a PSR-3 log event context from an Exception.
458 * Creates a structured array containing information about the provided
459 * exception that can be used to augment a log message sent to a PSR-3
462 * @param Exception|Throwable $e
465 public static function getLogContext( $e ) {
468 'exception_id' => WebRequest
::getRequestId(),
473 * Get a structured representation of an Exception.
475 * Returns an array of structured data (class, message, code, file,
476 * backtrace) derived from the given exception. The backtrace information
477 * will be redacted as per getRedactedTraceAsArray().
479 * @param Exception|Throwable $e
483 public static function getStructuredExceptionData( $e ) {
484 global $wgLogExceptionBacktrace;
486 'id' => WebRequest
::getRequestId(),
487 'type' => get_class( $e ),
488 'file' => $e->getFile(),
489 'line' => $e->getLine(),
490 'message' => $e->getMessage(),
491 'code' => $e->getCode(),
492 'url' => self
::getURL() ?
: null,
495 if ( $e instanceof ErrorException
&&
496 ( error_reporting() & $e->getSeverity() ) === 0
498 // Flag surpressed errors
499 $data['suppressed'] = true;
502 if ( $wgLogExceptionBacktrace ) {
503 $data['backtrace'] = self
::getRedactedTrace( $e );
506 $previous = $e->getPrevious();
507 if ( $previous !== null ) {
508 $data['previous'] = self
::getStructuredExceptionData( $previous );
515 * Serialize an Exception object to JSON.
517 * The JSON object will have keys 'id', 'file', 'line', 'message', and
518 * 'url'. These keys map to string values, with the exception of 'line',
519 * which is a number, and 'url', which may be either a string URL or or
520 * null if the exception did not occur in the context of serving a web
523 * If $wgLogExceptionBacktrace is true, it will also have a 'backtrace'
524 * key, mapped to the array return value of Exception::getTrace, but with
525 * each element in each frame's "args" array (if set) replaced with the
526 * argument's class name (if the argument is an object) or type name (if
527 * the argument is a PHP primitive).
529 * @par Sample JSON record ($wgLogExceptionBacktrace = false):
533 * "type": "MWException",
534 * "file": "/var/www/mediawiki/includes/cache/MessageCache.php",
536 * "message": "Non-string key given",
537 * "url": "/wiki/Main_Page"
541 * @par Sample JSON record ($wgLogExceptionBacktrace = true):
545 * "type": "MWException",
546 * "file": "/vagrant/mediawiki/includes/cache/MessageCache.php",
548 * "message": "Non-string key given",
549 * "url": "/wiki/Main_Page",
551 * "file": "/vagrant/mediawiki/extensions/VisualEditor/VisualEditor.hooks.php",
554 * "class": "MessageCache",
562 * @param Exception|Throwable $e
563 * @param bool $pretty Add non-significant whitespace to improve readability (default: false).
564 * @param int $escaping Bitfield consisting of FormatJson::.*_OK class constants.
565 * @return string|false JSON string if successful; false upon failure
567 public static function jsonSerializeException( $e, $pretty = false, $escaping = 0 ) {
568 $data = self
::getStructuredExceptionData( $e );
569 return FormatJson
::encode( $data, $pretty, $escaping );
573 * Log an exception to the exception log (if enabled).
575 * This method must not assume the exception is an MWException,
576 * it is also used to handle PHP exceptions or exceptions from other libraries.
579 * @param Exception|Throwable $e
581 public static function logException( $e ) {
582 if ( !( $e instanceof MWException
) ||
$e->isLoggable() ) {
583 $logger = LoggerFactory
::getInstance( 'exception' );
585 self
::getLogMessage( $e ),
586 self
::getLogContext( $e )
589 $json = self
::jsonSerializeException( $e, false, FormatJson
::ALL_OK
);
590 if ( $json !== false ) {
591 $logger = LoggerFactory
::getInstance( 'exception-json' );
592 $logger->error( $json, [ 'private' => true ] );
595 Hooks
::run( 'LogException', [ $e, false ] );
600 * Log an exception that wasn't thrown but made to wrap an error.
603 * @param ErrorException $e
604 * @param string $channel
606 protected static function logError( ErrorException
$e, $channel ) {
607 // The set_error_handler callback is independent from error_reporting.
608 // Filter out unwanted errors manually (e.g. when
609 // MediaWiki\suppressWarnings is active).
610 $suppressed = ( error_reporting() & $e->getSeverity() ) === 0;
611 if ( !$suppressed ) {
612 $logger = LoggerFactory
::getInstance( $channel );
614 self
::getLogMessage( $e ),
615 self
::getLogContext( $e )
619 // Include all errors in the json log (surpressed errors will be flagged)
620 $json = self
::jsonSerializeException( $e, false, FormatJson
::ALL_OK
);
621 if ( $json !== false ) {
622 $logger = LoggerFactory
::getInstance( "{$channel}-json" );
623 $logger->error( $json, [ 'private' => true ] );
626 Hooks
::run( 'LogException', [ $e, $suppressed ] );