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;
40 * Error types that, if unhandled, are fatal to the request.
42 * On PHP 7, these error types may be thrown as Error objects, which
43 * implement Throwable (but not Exception).
45 * On HHVM, these invoke the set_error_handler callback, similar to how
46 * (non-fatal) warnings and notices are reported, except that after this
47 * handler runs for fatal error tpyes, script execution stops!
49 * The user will be shown an HTTP 500 Internal Server Error.
50 * As such, these should be sent to MediaWiki's "fatal" or "exception"
51 * channel. Normally, the error handler logs them to the "error" channel.
53 * @var array $fatalErrorTypes
55 protected static $fatalErrorTypes = [
62 // E.g. "Catchable fatal error: Argument X must be Y, null given"
65 // HHVM's FATAL_ERROR constant
69 * @var bool $handledFatalCallback
71 protected static $handledFatalCallback = false;
74 * Install handlers with PHP.
76 public static function installHandler() {
77 set_exception_handler( 'MWExceptionHandler::handleUncaughtException' );
78 set_error_handler( 'MWExceptionHandler::handleError' );
80 // Reserve 16k of memory so we can report OOM fatals
81 self
::$reservedMemory = str_repeat( ' ', 16384 );
82 register_shutdown_function( 'MWExceptionHandler::handleFatalError' );
86 * Report an exception to the user
87 * @param Exception|Throwable $e
89 protected static function report( $e ) {
91 // Try and show the exception prettily, with the normal skin infrastructure
92 if ( $e instanceof MWException
) {
93 // Delegate to MWException until all subclasses are handled by
94 // MWExceptionRenderer and MWException::report() has been
98 MWExceptionRenderer
::output( $e, MWExceptionRenderer
::AS_PRETTY
);
100 } catch ( Exception
$e2 ) {
101 // Exception occurred from within exception handler
102 // Show a simpler message for the original exception,
103 // don't try to invoke report()
104 MWExceptionRenderer
::output( $e, MWExceptionRenderer
::AS_RAW
, $e2 );
109 * Roll back any open database transactions and log the stack trace of the exception
111 * This method is used to attempt to recover from exceptions
114 * @param Exception|Throwable $e
116 public static function rollbackMasterChangesAndLog( $e ) {
117 $services = MediaWikiServices
::getInstance();
118 if ( !$services->isServiceDisabled( 'DBLoadBalancerFactory' ) ) {
119 // Rollback DBs to avoid transaction notices. This might fail
120 // to rollback some databases due to connection issues or exceptions.
121 // However, any sane DB driver will rollback implicitly anyway.
123 $services->getDBLoadBalancerFactory()->rollbackMasterChanges( __METHOD__
);
124 } catch ( DBError
$e2 ) {
125 // If the DB is unreacheable, rollback() will throw an error
126 // and the error report() method might need messages from the DB,
127 // which would result in an exception loop. PHP may escalate such
128 // errors to "Exception thrown without a stack frame" fatals, but
129 // it's better to be explicit here.
130 self
::logException( $e2, self
::CAUGHT_BY_HANDLER
);
134 self
::logException( $e, self
::CAUGHT_BY_HANDLER
);
138 * Callback to use with PHP's set_exception_handler.
141 * @param Exception|Throwable $e
143 public static function handleUncaughtException( $e ) {
144 self
::handleException( $e );
146 // Make sure we don't claim success on exit for CLI scripts (T177414)
148 register_shutdown_function(
157 * Exception handler which simulates the appropriate catch() handling:
161 * } catch ( Exception $e ) {
163 * } catch ( Exception $e ) {
164 * echo $e->__toString();
168 * @param Exception|Throwable $e
170 public static function handleException( $e ) {
171 self
::rollbackMasterChangesAndLog( $e );
176 * Handler for set_error_handler() callback notifications.
178 * Receive a callback from the interpreter for a raised error, create an
179 * ErrorException, and log the exception to the 'error' logging
180 * channel(s). If the raised error is a fatal error type (only under HHVM)
181 * delegate to handleFatalError() instead.
185 * @param int $level Error level raised
186 * @param string $message
187 * @param string|null $file
188 * @param int|null $line
193 public static function handleError(
194 $level, $message, $file = null, $line = null
196 global $wgPropagateErrors;
198 if ( in_array( $level, self
::$fatalErrorTypes ) ) {
199 return self
::handleFatalError( ...func_get_args() );
202 // Map PHP error constant to a PSR-3 severity level.
203 // Avoid use of "DEBUG" or "INFO" levels, unless the
204 // error should evade error monitoring and alerts.
206 // To decide the log level, ask yourself: "Has the
207 // program's behaviour diverged from what the written
210 // For example, use of a deprecated method or violating a strict standard
211 // has no impact on functional behaviour (Warning). On the other hand,
212 // accessing an undefined variable makes behaviour diverge from what the
213 // author intended/expected. PHP recovers from an undefined variables by
214 // yielding null and continuing execution, but it remains a change in
215 // behaviour given the null was not part of the code and is likely not
220 case E_COMPILE_WARNING
:
221 $levelName = 'Warning';
222 $severity = LogLevel
::ERROR
;
225 $levelName = 'Notice';
226 $severity = LogLevel
::ERROR
;
229 // Used by wfWarn(), MWDebug::warning()
230 $levelName = 'Notice';
231 $severity = LogLevel
::WARNING
;
234 // Used by wfWarn(), MWDebug::warning()
235 $levelName = 'Warning';
236 $severity = LogLevel
::WARNING
;
239 $levelName = 'Strict Standards';
240 $severity = LogLevel
::WARNING
;
243 case E_USER_DEPRECATED
:
244 $levelName = 'Deprecated';
245 $severity = LogLevel
::WARNING
;
248 $levelName = 'Unknown error';
249 $severity = LogLevel
::ERROR
;
253 $e = new ErrorException( "PHP $levelName: $message", 0, $level, $file, $line );
254 self
::logError( $e, 'error', $severity );
256 // If $wgPropagateErrors is true return false so PHP shows/logs the error normally.
257 // Ignore $wgPropagateErrors if track_errors is set
258 // (which means someone is counting on regular PHP error handling behavior).
259 return !( $wgPropagateErrors ||
ini_get( 'track_errors' ) );
263 * Dual purpose callback used as both a set_error_handler() callback and
264 * a registered shutdown function. Receive a callback from the interpreter
265 * for a raised error or system shutdown, check for a fatal error, and log
266 * to the 'fatal' logging channel.
268 * Special handling is included for missing class errors as they may
269 * indicate that the user needs to install 3rd-party libraries via
270 * Composer or other means.
274 * @param int|null $level Error level raised
275 * @param string|null $message Error message
276 * @param string|null $file File that error was raised in
277 * @param int|null $line Line number error was raised at
278 * @param array|null $context Active symbol table point of error
279 * @param array|null $trace Backtrace at point of error (undocumented HHVM
281 * @return bool Always returns false
283 public static function handleFatalError(
284 $level = null, $message = null, $file = null, $line = null,
285 $context = null, $trace = null
287 // Free reserved memory so that we have space to process OOM
289 self
::$reservedMemory = null;
291 if ( $level === null ) {
292 // Called as a shutdown handler, get data from error_get_last()
293 if ( static::$handledFatalCallback ) {
294 // Already called once (probably as an error handler callback
295 // under HHVM) so don't log again.
299 $lastError = error_get_last();
300 if ( $lastError !== null ) {
301 $level = $lastError['type'];
302 $message = $lastError['message'];
303 $file = $lastError['file'];
304 $line = $lastError['line'];
311 if ( !in_array( $level, self
::$fatalErrorTypes ) ) {
312 // Only interested in fatal errors, others should have been
313 // handled by MWExceptionHandler::handleError
317 $url = WebRequest
::getGlobalRequestURL();
319 '[{exception_id}] {exception_url} PHP Fatal Error',
320 ( $line ||
$file ) ?
' from' : '',
321 $line ?
" line $line" : '',
322 ( $line && $file ) ?
' of' : '',
323 $file ?
" $file" : '',
326 $msg = implode( '', $msgParts );
328 // Look at message to see if this is a class not found failure
329 // HHVM: Class undefined: foo
330 // PHP5: Class 'foo' not found
331 if ( preg_match( "/Class (undefined: \w+|'\w+' not found)/", $message ) ) {
332 // phpcs:disable Generic.Files.LineLength
336 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.
338 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.
343 // We can't just create an exception and log it as it is likely that
344 // the interpreter has unwound the stack already. If that is true the
345 // stacktrace we would get would be functionally empty. If however we
346 // have been called as an error handler callback *and* HHVM is in use
347 // we will have been provided with a useful stacktrace that we can
349 $trace = $trace ?
: debug_backtrace();
350 $logger = LoggerFactory
::getInstance( 'fatal' );
351 $logger->error( $msg, [
352 'fatal_exception' => [
353 'class' => ErrorException
::class,
354 'message' => "PHP Fatal Error: {$message}",
358 'trace' => self
::prettyPrintTrace( self
::redactTrace( $trace ) ),
360 'exception_id' => WebRequest
::getRequestId(),
361 'exception_url' => $url,
362 'caught_by' => self
::CAUGHT_BY_HANDLER
365 // Remember call so we don't double process via HHVM's fatal
366 // notifications and the shutdown hook behavior
367 static::$handledFatalCallback = true;
372 * Generate a string representation of an exception's stack trace
374 * Like Exception::getTraceAsString, but replaces argument values with
375 * argument type or class name.
377 * @param Exception|Throwable $e
379 * @see prettyPrintTrace()
381 public static function getRedactedTraceAsString( $e ) {
382 return self
::prettyPrintTrace( self
::getRedactedTrace( $e ) );
386 * Generate a string representation of a stacktrace.
388 * @param array $trace
389 * @param string $pad Constant padding to add to each line of trace
393 public static function prettyPrintTrace( array $trace, $pad = '' ) {
397 foreach ( $trace as $level => $frame ) {
398 if ( isset( $frame['file'] ) && isset( $frame['line'] ) ) {
399 $text .= "{$pad}#{$level} {$frame['file']}({$frame['line']}): ";
401 // 'file' and 'line' are unset for calls via call_user_func
402 // (T57634) This matches behaviour of
403 // Exception::getTraceAsString to instead display "[internal
405 $text .= "{$pad}#{$level} [internal function]: ";
408 if ( isset( $frame['class'] ) && isset( $frame['type'] ) && isset( $frame['function'] ) ) {
409 $text .= $frame['class'] . $frame['type'] . $frame['function'];
410 } elseif ( isset( $frame['function'] ) ) {
411 $text .= $frame['function'];
413 $text .= 'NO_FUNCTION_GIVEN';
416 if ( isset( $frame['args'] ) ) {
417 $text .= '(' . implode( ', ', $frame['args'] ) . ")\n";
424 $text .= "{$pad}#{$level} {main}";
430 * Return a copy of an exception's backtrace as an array.
432 * Like Exception::getTrace, but replaces each element in each frame's
433 * argument array with the name of its class (if the element is an object)
434 * or its type (if the element is a PHP primitive).
437 * @param Exception|Throwable $e
440 public static function getRedactedTrace( $e ) {
441 return static::redactTrace( $e->getTrace() );
445 * Redact a stacktrace generated by Exception::getTrace(),
446 * debug_backtrace() or similar means. Replaces each element in each
447 * frame's argument array with the name of its class (if the element is an
448 * object) or its type (if the element is a PHP primitive).
451 * @param array $trace Stacktrace
452 * @return array Stacktrace with arugment values converted to data types
454 public static function redactTrace( array $trace ) {
455 return array_map( function ( $frame ) {
456 if ( isset( $frame['args'] ) ) {
457 $frame['args'] = array_map( function ( $arg ) {
458 return is_object( $arg ) ?
get_class( $arg ) : gettype( $arg );
466 * Get the ID for this exception.
468 * The ID is saved so that one can match the one output to the user (when
469 * $wgShowExceptionDetails is set to false), to the entry in the debug log.
472 * @deprecated since 1.27: Exception IDs are synonymous with request IDs.
473 * @param Exception|Throwable $e
476 public static function getLogId( $e ) {
477 wfDeprecated( __METHOD__
, '1.27' );
478 return WebRequest
::getRequestId();
482 * If the exception occurred in the course of responding to a request,
483 * returns the requested URL. Otherwise, returns false.
486 * @return string|false
488 public static function getURL() {
490 if ( !isset( $wgRequest ) ||
$wgRequest instanceof FauxRequest
) {
493 return $wgRequest->getRequestURL();
497 * Get a message formatting the exception message and its origin.
500 * @param Exception|Throwable $e
503 public static function getLogMessage( $e ) {
504 $id = WebRequest
::getRequestId();
505 $type = get_class( $e );
506 $file = $e->getFile();
507 $line = $e->getLine();
508 $message = $e->getMessage();
509 $url = self
::getURL() ?
: '[no req]';
511 return "[$id] $url $type from line $line of $file: $message";
515 * Get a normalised message for formatting with PSR-3 log event context.
517 * Must be used together with `getLogContext()` to be useful.
520 * @param Exception|Throwable $e
523 public static function getLogNormalMessage( $e ) {
524 $type = get_class( $e );
525 $file = $e->getFile();
526 $line = $e->getLine();
527 $message = $e->getMessage();
529 return "[{exception_id}] {exception_url} $type from line $line of $file: $message";
533 * @param Exception|Throwable $e
536 public static function getPublicLogMessage( $e ) {
537 $reqId = WebRequest
::getRequestId();
538 $type = get_class( $e );
539 return '[' . $reqId . '] '
540 . gmdate( 'Y-m-d H:i:s' ) . ': '
541 . 'Fatal exception of type "' . $type . '"';
545 * Get a PSR-3 log event context from an Exception.
547 * Creates a structured array containing information about the provided
548 * exception that can be used to augment a log message sent to a PSR-3
551 * @param Exception|Throwable $e
552 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
555 public static function getLogContext( $e, $catcher = self
::CAUGHT_BY_OTHER
) {
558 'exception_id' => WebRequest
::getRequestId(),
559 'exception_url' => self
::getURL() ?
: '[no req]',
560 'caught_by' => $catcher
565 * Get a structured representation of an Exception.
567 * Returns an array of structured data (class, message, code, file,
568 * backtrace) derived from the given exception. The backtrace information
569 * will be redacted as per getRedactedTraceAsArray().
571 * @param Exception|Throwable $e
572 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
576 public static function getStructuredExceptionData( $e, $catcher = self
::CAUGHT_BY_OTHER
) {
577 global $wgLogExceptionBacktrace;
580 'id' => WebRequest
::getRequestId(),
581 'type' => get_class( $e ),
582 'file' => $e->getFile(),
583 'line' => $e->getLine(),
584 'message' => $e->getMessage(),
585 'code' => $e->getCode(),
586 'url' => self
::getURL() ?
: null,
587 'caught_by' => $catcher
590 if ( $e instanceof ErrorException
&&
591 ( error_reporting() & $e->getSeverity() ) === 0
593 // Flag surpressed errors
594 $data['suppressed'] = true;
597 if ( $wgLogExceptionBacktrace ) {
598 $data['backtrace'] = self
::getRedactedTrace( $e );
601 $previous = $e->getPrevious();
602 if ( $previous !== null ) {
603 $data['previous'] = self
::getStructuredExceptionData( $previous, $catcher );
610 * Serialize an Exception object to JSON.
612 * The JSON object will have keys 'id', 'file', 'line', 'message', and
613 * 'url'. These keys map to string values, with the exception of 'line',
614 * which is a number, and 'url', which may be either a string URL or or
615 * null if the exception did not occur in the context of serving a web
618 * If $wgLogExceptionBacktrace is true, it will also have a 'backtrace'
619 * key, mapped to the array return value of Exception::getTrace, but with
620 * each element in each frame's "args" array (if set) replaced with the
621 * argument's class name (if the argument is an object) or type name (if
622 * the argument is a PHP primitive).
624 * @par Sample JSON record ($wgLogExceptionBacktrace = false):
628 * "type": "MWException",
629 * "file": "/var/www/mediawiki/includes/cache/MessageCache.php",
631 * "message": "Non-string key given",
632 * "url": "/wiki/Main_Page"
636 * @par Sample JSON record ($wgLogExceptionBacktrace = true):
640 * "type": "MWException",
641 * "file": "/vagrant/mediawiki/includes/cache/MessageCache.php",
643 * "message": "Non-string key given",
644 * "url": "/wiki/Main_Page",
646 * "file": "/vagrant/mediawiki/extensions/VisualEditor/VisualEditor.hooks.php",
649 * "class": "MessageCache",
657 * @param Exception|Throwable $e
658 * @param bool $pretty Add non-significant whitespace to improve readability (default: false).
659 * @param int $escaping Bitfield consisting of FormatJson::.*_OK class constants.
660 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
661 * @return string|false JSON string if successful; false upon failure
663 public static function jsonSerializeException(
664 $e, $pretty = false, $escaping = 0, $catcher = self
::CAUGHT_BY_OTHER
666 return FormatJson
::encode(
667 self
::getStructuredExceptionData( $e, $catcher ),
674 * Log an exception to the exception log (if enabled).
676 * This method must not assume the exception is an MWException,
677 * it is also used to handle PHP exceptions or exceptions from other libraries.
680 * @param Exception|Throwable $e
681 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
683 public static function logException( $e, $catcher = self
::CAUGHT_BY_OTHER
) {
684 if ( !( $e instanceof MWException
) ||
$e->isLoggable() ) {
685 $logger = LoggerFactory
::getInstance( 'exception' );
687 self
::getLogNormalMessage( $e ),
688 self
::getLogContext( $e, $catcher )
691 $json = self
::jsonSerializeException( $e, false, FormatJson
::ALL_OK
, $catcher );
692 if ( $json !== false ) {
693 $logger = LoggerFactory
::getInstance( 'exception-json' );
694 $logger->error( $json, [ 'private' => true ] );
697 Hooks
::run( 'LogException', [ $e, false ] );
702 * Log an exception that wasn't thrown but made to wrap an error.
705 * @param ErrorException $e
706 * @param string $channel
707 * @param string $level
709 protected static function logError(
710 ErrorException
$e, $channel, $level = LogLevel
::ERROR
712 $catcher = self
::CAUGHT_BY_HANDLER
;
713 // The set_error_handler callback is independent from error_reporting.
714 // Filter out unwanted errors manually (e.g. when
715 // Wikimedia\suppressWarnings is active).
716 $suppressed = ( error_reporting() & $e->getSeverity() ) === 0;
717 if ( !$suppressed ) {
718 $logger = LoggerFactory
::getInstance( $channel );
721 self
::getLogNormalMessage( $e ),
722 self
::getLogContext( $e, $catcher )
726 // Include all errors in the json log (surpressed errors will be flagged)
727 $json = self
::jsonSerializeException( $e, false, FormatJson
::ALL_OK
, $catcher );
728 if ( $json !== false ) {
729 $logger = LoggerFactory
::getInstance( "{$channel}-json" );
730 $logger->log( $level, $json, [ 'private' => true ] );
733 Hooks
::run( 'LogException', [ $e, $suppressed ] );