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
;
230 // Used by wfWarn(), MWDebug::warning()
231 $levelName = 'Warning';
232 $severity = LogLevel
::WARNING
;
235 $levelName = 'Strict Standards';
236 $severity = LogLevel
::WARNING
;
239 case E_USER_DEPRECATED
:
240 $levelName = 'Deprecated';
241 $severity = LogLevel
::WARNING
;
244 $levelName = 'Unknown error';
245 $severity = LogLevel
::ERROR
;
249 $e = new ErrorException( "PHP $levelName: $message", 0, $level, $file, $line );
250 self
::logError( $e, 'error', $severity );
252 // If $wgPropagateErrors is true return false so PHP shows/logs the error normally.
253 // Ignore $wgPropagateErrors if track_errors is set
254 // (which means someone is counting on regular PHP error handling behavior).
255 return !( $wgPropagateErrors ||
ini_get( 'track_errors' ) );
259 * Dual purpose callback used as both a set_error_handler() callback and
260 * a registered shutdown function. Receive a callback from the interpreter
261 * for a raised error or system shutdown, check for a fatal error, and log
262 * to the 'fatal' logging channel.
264 * Special handling is included for missing class errors as they may
265 * indicate that the user needs to install 3rd-party libraries via
266 * Composer or other means.
270 * @param int|null $level Error level raised
271 * @param string|null $message Error message
272 * @param string|null $file File that error was raised in
273 * @param int|null $line Line number error was raised at
274 * @param array|null $context Active symbol table point of error
275 * @param array|null $trace Backtrace at point of error (undocumented HHVM
277 * @return bool Always returns false
279 public static function handleFatalError(
280 $level = null, $message = null, $file = null, $line = null,
281 $context = null, $trace = null
283 // Free reserved memory so that we have space to process OOM
285 self
::$reservedMemory = null;
287 if ( $level === null ) {
288 // Called as a shutdown handler, get data from error_get_last()
289 if ( static::$handledFatalCallback ) {
290 // Already called once (probably as an error handler callback
291 // under HHVM) so don't log again.
295 $lastError = error_get_last();
296 if ( $lastError !== null ) {
297 $level = $lastError['type'];
298 $message = $lastError['message'];
299 $file = $lastError['file'];
300 $line = $lastError['line'];
307 if ( !in_array( $level, self
::$fatalErrorTypes ) ) {
308 // Only interested in fatal errors, others should have been
309 // handled by MWExceptionHandler::handleError
313 $url = WebRequest
::getGlobalRequestURL();
315 '[{exception_id}] {exception_url} PHP Fatal Error',
316 ( $line ||
$file ) ?
' from' : '',
317 $line ?
" line $line" : '',
318 ( $line && $file ) ?
' of' : '',
319 $file ?
" $file" : '',
322 $msg = implode( '', $msgParts );
324 // Look at message to see if this is a class not found failure
325 // HHVM: Class undefined: foo
326 // PHP5: Class 'foo' not found
327 if ( preg_match( "/Class (undefined: \w+|'\w+' not found)/", $message ) ) {
328 // phpcs:disable Generic.Files.LineLength
332 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.
334 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.
339 // We can't just create an exception and log it as it is likely that
340 // the interpreter has unwound the stack already. If that is true the
341 // stacktrace we would get would be functionally empty. If however we
342 // have been called as an error handler callback *and* HHVM is in use
343 // we will have been provided with a useful stacktrace that we can
345 $trace = $trace ?
: debug_backtrace();
346 $logger = LoggerFactory
::getInstance( 'fatal' );
347 $logger->error( $msg, [
348 'fatal_exception' => [
349 'class' => ErrorException
::class,
350 'message' => "PHP Fatal Error: {$message}",
354 'trace' => self
::prettyPrintTrace( self
::redactTrace( $trace ) ),
356 'exception_id' => WebRequest
::getRequestId(),
357 'exception_url' => $url,
358 'caught_by' => self
::CAUGHT_BY_HANDLER
361 // Remember call so we don't double process via HHVM's fatal
362 // notifications and the shutdown hook behavior
363 static::$handledFatalCallback = true;
368 * Generate a string representation of an exception's stack trace
370 * Like Exception::getTraceAsString, but replaces argument values with
371 * argument type or class name.
373 * @param Exception|Throwable $e
375 * @see prettyPrintTrace()
377 public static function getRedactedTraceAsString( $e ) {
378 return self
::prettyPrintTrace( self
::getRedactedTrace( $e ) );
382 * Generate a string representation of a stacktrace.
384 * @param array $trace
385 * @param string $pad Constant padding to add to each line of trace
389 public static function prettyPrintTrace( array $trace, $pad = '' ) {
393 foreach ( $trace as $level => $frame ) {
394 if ( isset( $frame['file'] ) && isset( $frame['line'] ) ) {
395 $text .= "{$pad}#{$level} {$frame['file']}({$frame['line']}): ";
397 // 'file' and 'line' are unset for calls via call_user_func
398 // (T57634) This matches behaviour of
399 // Exception::getTraceAsString to instead display "[internal
401 $text .= "{$pad}#{$level} [internal function]: ";
404 if ( isset( $frame['class'] ) && isset( $frame['type'] ) && isset( $frame['function'] ) ) {
405 $text .= $frame['class'] . $frame['type'] . $frame['function'];
406 } elseif ( isset( $frame['function'] ) ) {
407 $text .= $frame['function'];
409 $text .= 'NO_FUNCTION_GIVEN';
412 if ( isset( $frame['args'] ) ) {
413 $text .= '(' . implode( ', ', $frame['args'] ) . ")\n";
420 $text .= "{$pad}#{$level} {main}";
426 * Return a copy of an exception's backtrace as an array.
428 * Like Exception::getTrace, but replaces each element in each frame's
429 * argument array with the name of its class (if the element is an object)
430 * or its type (if the element is a PHP primitive).
433 * @param Exception|Throwable $e
436 public static function getRedactedTrace( $e ) {
437 return static::redactTrace( $e->getTrace() );
441 * Redact a stacktrace generated by Exception::getTrace(),
442 * debug_backtrace() or similar means. Replaces each element in each
443 * frame's argument array with the name of its class (if the element is an
444 * object) or its type (if the element is a PHP primitive).
447 * @param array $trace Stacktrace
448 * @return array Stacktrace with arugment values converted to data types
450 public static function redactTrace( array $trace ) {
451 return array_map( function ( $frame ) {
452 if ( isset( $frame['args'] ) ) {
453 $frame['args'] = array_map( function ( $arg ) {
454 return is_object( $arg ) ?
get_class( $arg ) : gettype( $arg );
462 * Get the ID for this exception.
464 * The ID is saved so that one can match the one output to the user (when
465 * $wgShowExceptionDetails is set to false), to the entry in the debug log.
468 * @deprecated since 1.27: Exception IDs are synonymous with request IDs.
469 * @param Exception|Throwable $e
472 public static function getLogId( $e ) {
473 wfDeprecated( __METHOD__
, '1.27' );
474 return WebRequest
::getRequestId();
478 * If the exception occurred in the course of responding to a request,
479 * returns the requested URL. Otherwise, returns false.
482 * @return string|false
484 public static function getURL() {
486 if ( !isset( $wgRequest ) ||
$wgRequest instanceof FauxRequest
) {
489 return $wgRequest->getRequestURL();
493 * Get a message formatting the exception message and its origin.
496 * @param Exception|Throwable $e
499 public static function getLogMessage( $e ) {
500 $id = WebRequest
::getRequestId();
501 $type = get_class( $e );
502 $file = $e->getFile();
503 $line = $e->getLine();
504 $message = $e->getMessage();
505 $url = self
::getURL() ?
: '[no req]';
507 return "[$id] $url $type from line $line of $file: $message";
511 * Get a normalised message for formatting with PSR-3 log event context.
513 * Must be used together with `getLogContext()` to be useful.
516 * @param Exception|Throwable $e
519 public static function getLogNormalMessage( $e ) {
520 $type = get_class( $e );
521 $file = $e->getFile();
522 $line = $e->getLine();
523 $message = $e->getMessage();
525 return "[{exception_id}] {exception_url} $type from line $line of $file: $message";
529 * @param Exception|Throwable $e
532 public static function getPublicLogMessage( $e ) {
533 $reqId = WebRequest
::getRequestId();
534 $type = get_class( $e );
535 return '[' . $reqId . '] '
536 . gmdate( 'Y-m-d H:i:s' ) . ': '
537 . 'Fatal exception of type "' . $type . '"';
541 * Get a PSR-3 log event context from an Exception.
543 * Creates a structured array containing information about the provided
544 * exception that can be used to augment a log message sent to a PSR-3
547 * @param Exception|Throwable $e
548 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
551 public static function getLogContext( $e, $catcher = self
::CAUGHT_BY_OTHER
) {
554 'exception_id' => WebRequest
::getRequestId(),
555 'exception_url' => self
::getURL() ?
: '[no req]',
556 'caught_by' => $catcher
561 * Get a structured representation of an Exception.
563 * Returns an array of structured data (class, message, code, file,
564 * backtrace) derived from the given exception. The backtrace information
565 * will be redacted as per getRedactedTraceAsArray().
567 * @param Exception|Throwable $e
568 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
572 public static function getStructuredExceptionData( $e, $catcher = self
::CAUGHT_BY_OTHER
) {
573 global $wgLogExceptionBacktrace;
576 'id' => WebRequest
::getRequestId(),
577 'type' => get_class( $e ),
578 'file' => $e->getFile(),
579 'line' => $e->getLine(),
580 'message' => $e->getMessage(),
581 'code' => $e->getCode(),
582 'url' => self
::getURL() ?
: null,
583 'caught_by' => $catcher
586 if ( $e instanceof ErrorException
&&
587 ( error_reporting() & $e->getSeverity() ) === 0
589 // Flag surpressed errors
590 $data['suppressed'] = true;
593 if ( $wgLogExceptionBacktrace ) {
594 $data['backtrace'] = self
::getRedactedTrace( $e );
597 $previous = $e->getPrevious();
598 if ( $previous !== null ) {
599 $data['previous'] = self
::getStructuredExceptionData( $previous, $catcher );
606 * Serialize an Exception object to JSON.
608 * The JSON object will have keys 'id', 'file', 'line', 'message', and
609 * 'url'. These keys map to string values, with the exception of 'line',
610 * which is a number, and 'url', which may be either a string URL or or
611 * null if the exception did not occur in the context of serving a web
614 * If $wgLogExceptionBacktrace is true, it will also have a 'backtrace'
615 * key, mapped to the array return value of Exception::getTrace, but with
616 * each element in each frame's "args" array (if set) replaced with the
617 * argument's class name (if the argument is an object) or type name (if
618 * the argument is a PHP primitive).
620 * @par Sample JSON record ($wgLogExceptionBacktrace = false):
624 * "type": "MWException",
625 * "file": "/var/www/mediawiki/includes/cache/MessageCache.php",
627 * "message": "Non-string key given",
628 * "url": "/wiki/Main_Page"
632 * @par Sample JSON record ($wgLogExceptionBacktrace = true):
636 * "type": "MWException",
637 * "file": "/vagrant/mediawiki/includes/cache/MessageCache.php",
639 * "message": "Non-string key given",
640 * "url": "/wiki/Main_Page",
642 * "file": "/vagrant/mediawiki/extensions/VisualEditor/VisualEditor.hooks.php",
645 * "class": "MessageCache",
653 * @param Exception|Throwable $e
654 * @param bool $pretty Add non-significant whitespace to improve readability (default: false).
655 * @param int $escaping Bitfield consisting of FormatJson::.*_OK class constants.
656 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
657 * @return string|false JSON string if successful; false upon failure
659 public static function jsonSerializeException(
660 $e, $pretty = false, $escaping = 0, $catcher = self
::CAUGHT_BY_OTHER
662 return FormatJson
::encode(
663 self
::getStructuredExceptionData( $e, $catcher ),
670 * Log an exception to the exception log (if enabled).
672 * This method must not assume the exception is an MWException,
673 * it is also used to handle PHP exceptions or exceptions from other libraries.
676 * @param Exception|Throwable $e
677 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
679 public static function logException( $e, $catcher = self
::CAUGHT_BY_OTHER
) {
680 if ( !( $e instanceof MWException
) ||
$e->isLoggable() ) {
681 $logger = LoggerFactory
::getInstance( 'exception' );
683 self
::getLogNormalMessage( $e ),
684 self
::getLogContext( $e, $catcher )
687 $json = self
::jsonSerializeException( $e, false, FormatJson
::ALL_OK
, $catcher );
688 if ( $json !== false ) {
689 $logger = LoggerFactory
::getInstance( 'exception-json' );
690 $logger->error( $json, [ 'private' => true ] );
693 Hooks
::run( 'LogException', [ $e, false ] );
698 * Log an exception that wasn't thrown but made to wrap an error.
701 * @param ErrorException $e
702 * @param string $channel
703 * @param string $level
705 protected static function logError(
706 ErrorException
$e, $channel, $level = LogLevel
::ERROR
708 $catcher = self
::CAUGHT_BY_HANDLER
;
709 // The set_error_handler callback is independent from error_reporting.
710 // Filter out unwanted errors manually (e.g. when
711 // Wikimedia\suppressWarnings is active).
712 $suppressed = ( error_reporting() & $e->getSeverity() ) === 0;
713 if ( !$suppressed ) {
714 $logger = LoggerFactory
::getInstance( $channel );
717 self
::getLogNormalMessage( $e ),
718 self
::getLogContext( $e, $catcher )
722 // Include all errors in the json log (surpressed errors will be flagged)
723 $json = self
::jsonSerializeException( $e, false, FormatJson
::ALL_OK
, $catcher );
724 if ( $json !== false ) {
725 $logger = LoggerFactory
::getInstance( "{$channel}-json" );
726 $logger->log( $level, $json, [ 'private' => true ] );
729 Hooks
::run( 'LogException', [ $e, $suppressed ] );