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 * Roll back any open database transactions and log the stack trace of the exception
88 * This method is used to attempt to recover from exceptions
91 * @param Exception|Throwable $e
93 public static function rollbackMasterChangesAndLog( $e ) {
94 $services = MediaWikiServices
::getInstance();
95 if ( !$services->isServiceDisabled( 'DBLoadBalancerFactory' ) ) {
96 // Rollback DBs to avoid transaction notices. This might fail
97 // to rollback some databases due to connection issues or exceptions.
98 // However, any sane DB driver will rollback implicitly anyway.
100 $services->getDBLoadBalancerFactory()->rollbackMasterChanges( __METHOD__
);
101 } catch ( DBError
$e2 ) {
102 // If the DB is unreacheable, rollback() will throw an error
103 // and the error report() method might need messages from the DB,
104 // which would result in an exception loop. PHP may escalate such
105 // errors to "Exception thrown without a stack frame" fatals, but
106 // it's better to be explicit here.
107 self
::logException( $e2, self
::CAUGHT_BY_HANDLER
);
111 self
::logException( $e, self
::CAUGHT_BY_HANDLER
);
115 * Exception handler which simulates the appropriate catch() handling:
119 * } catch ( Exception $e ) {
121 * } catch ( Exception $e ) {
122 * echo $e->__toString();
126 * @param Exception|Throwable $e
128 public static function handleException( $e ) {
129 self
::rollbackMasterChangesAndLog( $e );
134 * Handler for set_error_handler() callback notifications.
136 * Receive a callback from the interpreter for a raised error, create an
137 * ErrorException, and log the exception to the 'error' logging
138 * channel(s). If the raised error is a fatal error type (only under HHVM)
139 * delegate to handleFatalError() instead.
143 * @param int $level Error level raised
144 * @param string $message
145 * @param string $file
151 public static function handleError(
152 $level, $message, $file = null, $line = null
154 if ( in_array( $level, self
::$fatalErrorTypes ) ) {
155 return call_user_func_array(
156 'MWExceptionHandler::handleFatalError', func_get_args()
160 // Map error constant to error name (reverse-engineer PHP error
163 case E_RECOVERABLE_ERROR
:
164 $levelName = 'Error';
165 $severity = LogLevel
::ERROR
;
169 case E_COMPILE_WARNING
:
171 $levelName = 'Warning';
172 $severity = LogLevel
::WARNING
;
176 $levelName = 'Notice';
177 $severity = LogLevel
::INFO
;
180 $levelName = 'Strict Standards';
181 $severity = LogLevel
::DEBUG
;
184 case E_USER_DEPRECATED
:
185 $levelName = 'Deprecated';
186 $severity = LogLevel
::INFO
;
189 $levelName = 'Unknown error';
190 $severity = LogLevel
::ERROR
;
194 $e = new ErrorException( "PHP $levelName: $message", 0, $level, $file, $line );
195 self
::logError( $e, 'error', $severity );
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, [
283 'fatal_exception' => [
284 'class' => 'ErrorException',
285 'message' => "PHP Fatal Error: {$message}",
289 'trace' => static::redactTrace( $trace ),
291 'exception_id' => wfRandomString( 8 ),
292 'caught_by' => self
::CAUGHT_BY_HANDLER
295 // Remember call so we don't double process via HHVM's fatal
296 // notifications and the shutdown hook behavior
297 static::$handledFatalCallback = true;
302 * Generate a string representation of an exception's stack trace
304 * Like Exception::getTraceAsString, but replaces argument values with
305 * argument type or class name.
307 * @param Exception|Throwable $e
309 * @see prettyPrintTrace()
311 public static function getRedactedTraceAsString( $e ) {
312 return self
::prettyPrintTrace( self
::getRedactedTrace( $e ) );
316 * Generate a string representation of a stacktrace.
318 * @param array $trace
319 * @param string $pad Constant padding to add to each line of trace
323 public static function prettyPrintTrace( array $trace, $pad = '' ) {
327 foreach ( $trace as $level => $frame ) {
328 if ( isset( $frame['file'] ) && isset( $frame['line'] ) ) {
329 $text .= "{$pad}#{$level} {$frame['file']}({$frame['line']}): ";
331 // 'file' and 'line' are unset for calls via call_user_func
332 // (T57634) This matches behaviour of
333 // Exception::getTraceAsString to instead display "[internal
335 $text .= "{$pad}#{$level} [internal function]: ";
338 if ( isset( $frame['class'] ) && isset( $frame['type'] ) && isset( $frame['function'] ) ) {
339 $text .= $frame['class'] . $frame['type'] . $frame['function'];
340 } elseif ( isset( $frame['function'] ) ) {
341 $text .= $frame['function'];
343 $text .= 'NO_FUNCTION_GIVEN';
346 if ( isset( $frame['args'] ) ) {
347 $text .= '(' . implode( ', ', $frame['args'] ) . ")\n";
354 $text .= "{$pad}#{$level} {main}";
360 * Return a copy of an exception's backtrace as an array.
362 * Like Exception::getTrace, but replaces each element in each frame's
363 * argument array with the name of its class (if the element is an object)
364 * or its type (if the element is a PHP primitive).
367 * @param Exception|Throwable $e
370 public static function getRedactedTrace( $e ) {
371 return static::redactTrace( $e->getTrace() );
375 * Redact a stacktrace generated by Exception::getTrace(),
376 * debug_backtrace() or similar means. Replaces each element in each
377 * frame's argument array with the name of its class (if the element is an
378 * object) or its type (if the element is a PHP primitive).
381 * @param array $trace Stacktrace
382 * @return array Stacktrace with arugment values converted to data types
384 public static function redactTrace( array $trace ) {
385 return array_map( function ( $frame ) {
386 if ( isset( $frame['args'] ) ) {
387 $frame['args'] = array_map( function ( $arg ) {
388 return is_object( $arg ) ?
get_class( $arg ) : gettype( $arg );
396 * Get the ID for this exception.
398 * The ID is saved so that one can match the one output to the user (when
399 * $wgShowExceptionDetails is set to false), to the entry in the debug log.
402 * @deprecated since 1.27: Exception IDs are synonymous with request IDs.
403 * @param Exception|Throwable $e
406 public static function getLogId( $e ) {
407 wfDeprecated( __METHOD__
, '1.27' );
408 return WebRequest
::getRequestId();
412 * If the exception occurred in the course of responding to a request,
413 * returns the requested URL. Otherwise, returns false.
416 * @return string|false
418 public static function getURL() {
420 if ( !isset( $wgRequest ) ||
$wgRequest instanceof FauxRequest
) {
423 return $wgRequest->getRequestURL();
427 * Get a message formatting the exception message and its origin.
430 * @param Exception|Throwable $e
433 public static function getLogMessage( $e ) {
434 $id = WebRequest
::getRequestId();
435 $type = get_class( $e );
436 $file = $e->getFile();
437 $line = $e->getLine();
438 $message = $e->getMessage();
439 $url = self
::getURL() ?
: '[no req]';
441 return "[$id] $url $type from line $line of $file: $message";
445 * @param Exception|Throwable $e
448 public static function getPublicLogMessage( $e ) {
449 $reqId = WebRequest
::getRequestId();
450 $type = get_class( $e );
451 return '[' . $reqId . '] '
452 . gmdate( 'Y-m-d H:i:s' ) . ': '
453 . 'Fatal exception of type "' . $type . '"';
457 * Get a PSR-3 log event context from an Exception.
459 * Creates a structured array containing information about the provided
460 * exception that can be used to augment a log message sent to a PSR-3
463 * @param Exception|Throwable $e
464 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
467 public static function getLogContext( $e, $catcher = self
::CAUGHT_BY_OTHER
) {
470 'exception_id' => WebRequest
::getRequestId(),
471 'caught_by' => $catcher
476 * Get a structured representation of an Exception.
478 * Returns an array of structured data (class, message, code, file,
479 * backtrace) derived from the given exception. The backtrace information
480 * will be redacted as per getRedactedTraceAsArray().
482 * @param Exception|Throwable $e
483 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
487 public static function getStructuredExceptionData( $e, $catcher = self
::CAUGHT_BY_OTHER
) {
488 global $wgLogExceptionBacktrace;
491 'id' => WebRequest
::getRequestId(),
492 'type' => get_class( $e ),
493 'file' => $e->getFile(),
494 'line' => $e->getLine(),
495 'message' => $e->getMessage(),
496 'code' => $e->getCode(),
497 'url' => self
::getURL() ?
: null,
498 'caught_by' => $catcher
501 if ( $e instanceof ErrorException
&&
502 ( error_reporting() & $e->getSeverity() ) === 0
504 // Flag surpressed errors
505 $data['suppressed'] = true;
508 if ( $wgLogExceptionBacktrace ) {
509 $data['backtrace'] = self
::getRedactedTrace( $e );
512 $previous = $e->getPrevious();
513 if ( $previous !== null ) {
514 $data['previous'] = self
::getStructuredExceptionData( $previous, $catcher );
521 * Serialize an Exception object to JSON.
523 * The JSON object will have keys 'id', 'file', 'line', 'message', and
524 * 'url'. These keys map to string values, with the exception of 'line',
525 * which is a number, and 'url', which may be either a string URL or or
526 * null if the exception did not occur in the context of serving a web
529 * If $wgLogExceptionBacktrace is true, it will also have a 'backtrace'
530 * key, mapped to the array return value of Exception::getTrace, but with
531 * each element in each frame's "args" array (if set) replaced with the
532 * argument's class name (if the argument is an object) or type name (if
533 * the argument is a PHP primitive).
535 * @par Sample JSON record ($wgLogExceptionBacktrace = false):
539 * "type": "MWException",
540 * "file": "/var/www/mediawiki/includes/cache/MessageCache.php",
542 * "message": "Non-string key given",
543 * "url": "/wiki/Main_Page"
547 * @par Sample JSON record ($wgLogExceptionBacktrace = true):
551 * "type": "MWException",
552 * "file": "/vagrant/mediawiki/includes/cache/MessageCache.php",
554 * "message": "Non-string key given",
555 * "url": "/wiki/Main_Page",
557 * "file": "/vagrant/mediawiki/extensions/VisualEditor/VisualEditor.hooks.php",
560 * "class": "MessageCache",
568 * @param Exception|Throwable $e
569 * @param bool $pretty Add non-significant whitespace to improve readability (default: false).
570 * @param int $escaping Bitfield consisting of FormatJson::.*_OK class constants.
571 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
572 * @return string|false JSON string if successful; false upon failure
574 public static function jsonSerializeException(
575 $e, $pretty = false, $escaping = 0, $catcher = self
::CAUGHT_BY_OTHER
577 return FormatJson
::encode(
578 self
::getStructuredExceptionData( $e, $catcher ),
585 * Log an exception to the exception log (if enabled).
587 * This method must not assume the exception is an MWException,
588 * it is also used to handle PHP exceptions or exceptions from other libraries.
591 * @param Exception|Throwable $e
592 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
594 public static function logException( $e, $catcher = self
::CAUGHT_BY_OTHER
) {
595 if ( !( $e instanceof MWException
) ||
$e->isLoggable() ) {
596 $logger = LoggerFactory
::getInstance( 'exception' );
598 self
::getLogMessage( $e ),
599 self
::getLogContext( $e, $catcher )
602 $json = self
::jsonSerializeException( $e, false, FormatJson
::ALL_OK
, $catcher );
603 if ( $json !== false ) {
604 $logger = LoggerFactory
::getInstance( 'exception-json' );
605 $logger->error( $json, [ 'private' => true ] );
608 Hooks
::run( 'LogException', [ $e, false ] );
613 * Log an exception that wasn't thrown but made to wrap an error.
616 * @param ErrorException $e
617 * @param string $channel
618 * @param string $level
620 protected static function logError(
621 ErrorException
$e, $channel, $level = LogLevel
::ERROR
623 $catcher = self
::CAUGHT_BY_HANDLER
;
624 // The set_error_handler callback is independent from error_reporting.
625 // Filter out unwanted errors manually (e.g. when
626 // MediaWiki\suppressWarnings is active).
627 $suppressed = ( error_reporting() & $e->getSeverity() ) === 0;
628 if ( !$suppressed ) {
629 $logger = LoggerFactory
::getInstance( $channel );
632 self
::getLogMessage( $e ),
633 self
::getLogContext( $e, $catcher )
637 // Include all errors in the json log (surpressed errors will be flagged)
638 $json = self
::jsonSerializeException( $e, false, FormatJson
::ALL_OK
, $catcher );
639 if ( $json !== false ) {
640 $logger = LoggerFactory
::getInstance( "{$channel}-json" );
641 $logger->log( $level, $json, [ 'private' => true ] );
644 Hooks
::run( 'LogException', [ $e, $suppressed ] );