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
;
26 * Handler class for MWExceptions
29 class MWExceptionHandler
{
30 const CAUGHT_BY_HANDLER
= 'mwe_handler'; // error reported by this exception handler
31 const CAUGHT_BY_OTHER
= 'other'; // error reported by direct logException() call
34 * @var string $reservedMemory
36 protected static $reservedMemory;
38 * @var array $fatalErrorTypes
40 protected static $fatalErrorTypes = [
41 E_ERROR
, E_PARSE
, E_CORE_ERROR
, E_COMPILE_ERROR
, E_USER_ERROR
,
42 /* HHVM's FATAL_ERROR level */ 16777217,
45 * @var bool $handledFatalCallback
47 protected static $handledFatalCallback = false;
50 * Install handlers with PHP.
52 public static function installHandler() {
53 set_exception_handler( 'MWExceptionHandler::handleException' );
54 set_error_handler( 'MWExceptionHandler::handleError' );
56 // Reserve 16k of memory so we can report OOM fatals
57 self
::$reservedMemory = str_repeat( ' ', 16384 );
58 register_shutdown_function( 'MWExceptionHandler::handleFatalError' );
62 * Report an exception to the user
63 * @param Exception|Throwable $e
65 protected static function report( $e ) {
67 // Try and show the exception prettily, with the normal skin infrastructure
68 if ( $e instanceof MWException
) {
69 // Delegate to MWException until all subclasses are handled by
70 // MWExceptionRenderer and MWException::report() has been
74 MWExceptionRenderer
::output( $e, MWExceptionRenderer
::AS_PRETTY
);
76 } catch ( Exception
$e2 ) {
77 // Exception occurred from within exception handler
78 // Show a simpler message for the original exception,
79 // don't try to invoke report()
80 MWExceptionRenderer
::output( $e, MWExceptionRenderer
::AS_RAW
, $e2 );
85 * If there are any open database transactions, roll them back and log
86 * the stack trace of the exception that should have been caught so the
87 * transaction could be aborted properly.
90 * @param Exception|Throwable $e
92 public static function rollbackMasterChangesAndLog( $e ) {
93 $services = MediaWikiServices
::getInstance();
94 if ( $services->isServiceDisabled( 'DBLoadBalancerFactory' ) ) {
98 $lbFactory = $services->getDBLoadBalancerFactory();
99 if ( $lbFactory->hasMasterChanges() ) {
100 $logger = LoggerFactory
::getInstance( 'Bug56269' );
102 'Exception thrown with an uncommited database transaction: ' .
103 self
::getLogMessage( $e ),
104 self
::getLogContext( $e )
107 $lbFactory->rollbackMasterChanges( __METHOD__
);
111 * Exception handler which simulates the appropriate catch() handling:
115 * } catch ( Exception $e ) {
117 * } catch ( Exception $e ) {
118 * echo $e->__toString();
122 * @param Exception|Throwable $e
124 public static function handleException( $e ) {
126 // Rollback DBs to avoid transaction notices. This may fail
127 // to rollback some DB due to connection issues or exceptions.
128 // However, any sane DB driver will rollback implicitly anyway.
129 self
::rollbackMasterChangesAndLog( $e );
130 } catch ( DBError
$e2 ) {
131 // If the DB is unreacheable, rollback() will throw an error
132 // and the error report() method might need messages from the DB,
133 // which would result in an exception loop. PHP may escalate such
134 // errors to "Exception thrown without a stack frame" fatals, but
135 // it's better to be explicit here.
136 self
::logException( $e2, self
::CAUGHT_BY_HANDLER
);
139 self
::logException( $e, self
::CAUGHT_BY_HANDLER
);
142 // Exit value should be nonzero for the benefit of shell jobs
147 * Handler for set_error_handler() callback notifications.
149 * Receive a callback from the interpreter for a raised error, create an
150 * ErrorException, and log the exception to the 'error' logging
151 * channel(s). If the raised error is a fatal error type (only under HHVM)
152 * delegate to handleFatalError() instead.
156 * @param int $level Error level raised
157 * @param string $message
158 * @param string $file
164 public static function handleError(
165 $level, $message, $file = null, $line = null
167 if ( in_array( $level, self
::$fatalErrorTypes ) ) {
168 return call_user_func_array(
169 'MWExceptionHandler::handleFatalError', func_get_args()
173 // Map error constant to error name (reverse-engineer PHP error
176 case E_RECOVERABLE_ERROR
:
177 $levelName = 'Error';
178 $severity = LogLevel
::ERROR
;
182 case E_COMPILE_WARNING
:
184 $levelName = 'Warning';
185 $severity = LogLevel
::WARNING
;
189 $levelName = 'Notice';
190 $severity = LogLevel
::INFO
;
193 $levelName = 'Strict Standards';
194 $severity = LogLevel
::DEBUG
;
197 case E_USER_DEPRECATED
:
198 $levelName = 'Deprecated';
199 $severity = LogLevel
::INFO
;
202 $levelName = 'Unknown error';
203 $severity = LogLevel
::ERROR
;
207 $e = new ErrorException( "PHP $levelName: $message", 0, $level, $file, $line );
208 self
::logError( $e, 'error', $severity );
210 // This handler is for logging only. Return false will instruct PHP
211 // to continue regular handling.
216 * Dual purpose callback used as both a set_error_handler() callback and
217 * a registered shutdown function. Receive a callback from the interpreter
218 * for a raised error or system shutdown, check for a fatal error, and log
219 * to the 'fatal' logging channel.
221 * Special handling is included for missing class errors as they may
222 * indicate that the user needs to install 3rd-party libraries via
223 * Composer or other means.
227 * @param int $level Error level raised
228 * @param string $message Error message
229 * @param string $file File that error was raised in
230 * @param int $line Line number error was raised at
231 * @param array $context Active symbol table point of error
232 * @param array $trace Backtrace at point of error (undocumented HHVM
234 * @return bool Always returns false
236 public static function handleFatalError(
237 $level = null, $message = null, $file = null, $line = null,
238 $context = null, $trace = null
240 // Free reserved memory so that we have space to process OOM
242 self
::$reservedMemory = null;
244 if ( $level === null ) {
245 // Called as a shutdown handler, get data from error_get_last()
246 if ( static::$handledFatalCallback ) {
247 // Already called once (probably as an error handler callback
248 // under HHVM) so don't log again.
252 $lastError = error_get_last();
253 if ( $lastError !== null ) {
254 $level = $lastError['type'];
255 $message = $lastError['message'];
256 $file = $lastError['file'];
257 $line = $lastError['line'];
264 if ( !in_array( $level, self
::$fatalErrorTypes ) ) {
265 // Only interested in fatal errors, others should have been
266 // handled by MWExceptionHandler::handleError
270 $msg = "[{exception_id}] PHP Fatal Error: {$message}";
272 // Look at message to see if this is a class not found failure
273 // HHVM: Class undefined: foo
274 // PHP5: Class 'foo' not found
275 if ( preg_match( "/Class (undefined: \w+|'\w+' not found)/", $msg ) ) {
276 // @codingStandardsIgnoreStart Generic.Files.LineLength.TooLong
280 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.
282 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.
284 // @codingStandardsIgnoreEnd
287 // We can't just create an exception and log it as it is likely that
288 // the interpreter has unwound the stack already. If that is true the
289 // stacktrace we would get would be functionally empty. If however we
290 // have been called as an error handler callback *and* HHVM is in use
291 // we will have been provided with a useful stacktrace that we can
293 $trace = $trace ?
: debug_backtrace();
294 $logger = LoggerFactory
::getInstance( 'fatal' );
295 $logger->error( $msg, [
296 'fatal_exception' => [
297 'class' => 'ErrorException',
298 'message' => "PHP Fatal Error: {$message}",
302 'trace' => static::redactTrace( $trace ),
304 'exception_id' => wfRandomString( 8 ),
305 'caught_by' => self
::CAUGHT_BY_HANDLER
308 // Remember call so we don't double process via HHVM's fatal
309 // notifications and the shutdown hook behavior
310 static::$handledFatalCallback = true;
315 * Generate a string representation of an exception's stack trace
317 * Like Exception::getTraceAsString, but replaces argument values with
318 * argument type or class name.
320 * @param Exception|Throwable $e
322 * @see prettyPrintTrace()
324 public static function getRedactedTraceAsString( $e ) {
325 return self
::prettyPrintTrace( self
::getRedactedTrace( $e ) );
329 * Generate a string representation of a stacktrace.
331 * @param array $trace
332 * @param string $pad Constant padding to add to each line of trace
336 public static function prettyPrintTrace( array $trace, $pad = '' ) {
340 foreach ( $trace as $level => $frame ) {
341 if ( isset( $frame['file'] ) && isset( $frame['line'] ) ) {
342 $text .= "{$pad}#{$level} {$frame['file']}({$frame['line']}): ";
344 // 'file' and 'line' are unset for calls via call_user_func
345 // (T57634) This matches behaviour of
346 // Exception::getTraceAsString to instead display "[internal
348 $text .= "{$pad}#{$level} [internal function]: ";
351 if ( isset( $frame['class'] ) && isset( $frame['type'] ) && isset( $frame['function'] ) ) {
352 $text .= $frame['class'] . $frame['type'] . $frame['function'];
353 } elseif ( isset( $frame['function'] ) ) {
354 $text .= $frame['function'];
356 $text .= 'NO_FUNCTION_GIVEN';
359 if ( isset( $frame['args'] ) ) {
360 $text .= '(' . implode( ', ', $frame['args'] ) . ")\n";
367 $text .= "{$pad}#{$level} {main}";
373 * Return a copy of an exception's backtrace as an array.
375 * Like Exception::getTrace, but replaces each element in each frame's
376 * argument array with the name of its class (if the element is an object)
377 * or its type (if the element is a PHP primitive).
380 * @param Exception|Throwable $e
383 public static function getRedactedTrace( $e ) {
384 return static::redactTrace( $e->getTrace() );
388 * Redact a stacktrace generated by Exception::getTrace(),
389 * debug_backtrace() or similar means. Replaces each element in each
390 * frame's argument array with the name of its class (if the element is an
391 * object) or its type (if the element is a PHP primitive).
394 * @param array $trace Stacktrace
395 * @return array Stacktrace with arugment values converted to data types
397 public static function redactTrace( array $trace ) {
398 return array_map( function ( $frame ) {
399 if ( isset( $frame['args'] ) ) {
400 $frame['args'] = array_map( function ( $arg ) {
401 return is_object( $arg ) ?
get_class( $arg ) : gettype( $arg );
409 * Get the ID for this exception.
411 * The ID is saved so that one can match the one output to the user (when
412 * $wgShowExceptionDetails is set to false), to the entry in the debug log.
415 * @deprecated since 1.27: Exception IDs are synonymous with request IDs.
416 * @param Exception|Throwable $e
419 public static function getLogId( $e ) {
420 wfDeprecated( __METHOD__
, '1.27' );
421 return WebRequest
::getRequestId();
425 * If the exception occurred in the course of responding to a request,
426 * returns the requested URL. Otherwise, returns false.
429 * @return string|false
431 public static function getURL() {
433 if ( !isset( $wgRequest ) ||
$wgRequest instanceof FauxRequest
) {
436 return $wgRequest->getRequestURL();
440 * Get a message formatting the exception message and its origin.
443 * @param Exception|Throwable $e
446 public static function getLogMessage( $e ) {
447 $id = WebRequest
::getRequestId();
448 $type = get_class( $e );
449 $file = $e->getFile();
450 $line = $e->getLine();
451 $message = $e->getMessage();
452 $url = self
::getURL() ?
: '[no req]';
454 return "[$id] $url $type from line $line of $file: $message";
458 * @param Exception|Throwable $e
461 public static function getPublicLogMessage( $e ) {
462 $reqId = WebRequest
::getRequestId();
463 $type = get_class( $e );
464 return '[' . $reqId . '] '
465 . gmdate( 'Y-m-d H:i:s' ) . ': '
466 . 'Fatal exception of type "' . $type . '"';
470 * Get a PSR-3 log event context from an Exception.
472 * Creates a structured array containing information about the provided
473 * exception that can be used to augment a log message sent to a PSR-3
476 * @param Exception|Throwable $e
477 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
480 public static function getLogContext( $e, $catcher = self
::CAUGHT_BY_OTHER
) {
483 'exception_id' => WebRequest
::getRequestId(),
484 'caught_by' => $catcher
489 * Get a structured representation of an Exception.
491 * Returns an array of structured data (class, message, code, file,
492 * backtrace) derived from the given exception. The backtrace information
493 * will be redacted as per getRedactedTraceAsArray().
495 * @param Exception|Throwable $e
496 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
500 public static function getStructuredExceptionData( $e, $catcher = self
::CAUGHT_BY_OTHER
) {
501 global $wgLogExceptionBacktrace;
504 'id' => WebRequest
::getRequestId(),
505 'type' => get_class( $e ),
506 'file' => $e->getFile(),
507 'line' => $e->getLine(),
508 'message' => $e->getMessage(),
509 'code' => $e->getCode(),
510 'url' => self
::getURL() ?
: null,
511 'caught_by' => $catcher
514 if ( $e instanceof ErrorException
&&
515 ( error_reporting() & $e->getSeverity() ) === 0
517 // Flag surpressed errors
518 $data['suppressed'] = true;
521 if ( $wgLogExceptionBacktrace ) {
522 $data['backtrace'] = self
::getRedactedTrace( $e );
525 $previous = $e->getPrevious();
526 if ( $previous !== null ) {
527 $data['previous'] = self
::getStructuredExceptionData( $previous, $catcher );
534 * Serialize an Exception object to JSON.
536 * The JSON object will have keys 'id', 'file', 'line', 'message', and
537 * 'url'. These keys map to string values, with the exception of 'line',
538 * which is a number, and 'url', which may be either a string URL or or
539 * null if the exception did not occur in the context of serving a web
542 * If $wgLogExceptionBacktrace is true, it will also have a 'backtrace'
543 * key, mapped to the array return value of Exception::getTrace, but with
544 * each element in each frame's "args" array (if set) replaced with the
545 * argument's class name (if the argument is an object) or type name (if
546 * the argument is a PHP primitive).
548 * @par Sample JSON record ($wgLogExceptionBacktrace = false):
552 * "type": "MWException",
553 * "file": "/var/www/mediawiki/includes/cache/MessageCache.php",
555 * "message": "Non-string key given",
556 * "url": "/wiki/Main_Page"
560 * @par Sample JSON record ($wgLogExceptionBacktrace = true):
564 * "type": "MWException",
565 * "file": "/vagrant/mediawiki/includes/cache/MessageCache.php",
567 * "message": "Non-string key given",
568 * "url": "/wiki/Main_Page",
570 * "file": "/vagrant/mediawiki/extensions/VisualEditor/VisualEditor.hooks.php",
573 * "class": "MessageCache",
581 * @param Exception|Throwable $e
582 * @param bool $pretty Add non-significant whitespace to improve readability (default: false).
583 * @param int $escaping Bitfield consisting of FormatJson::.*_OK class constants.
584 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
585 * @return string|false JSON string if successful; false upon failure
587 public static function jsonSerializeException(
588 $e, $pretty = false, $escaping = 0, $catcher = self
::CAUGHT_BY_OTHER
590 return FormatJson
::encode(
591 self
::getStructuredExceptionData( $e, $catcher ),
598 * Log an exception to the exception log (if enabled).
600 * This method must not assume the exception is an MWException,
601 * it is also used to handle PHP exceptions or exceptions from other libraries.
604 * @param Exception|Throwable $e
605 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
607 public static function logException( $e, $catcher = self
::CAUGHT_BY_OTHER
) {
608 if ( !( $e instanceof MWException
) ||
$e->isLoggable() ) {
609 $logger = LoggerFactory
::getInstance( 'exception' );
611 self
::getLogMessage( $e ),
612 self
::getLogContext( $e, $catcher )
615 $json = self
::jsonSerializeException( $e, false, FormatJson
::ALL_OK
, $catcher );
616 if ( $json !== false ) {
617 $logger = LoggerFactory
::getInstance( 'exception-json' );
618 $logger->error( $json, [ 'private' => true ] );
621 Hooks
::run( 'LogException', [ $e, false ] );
626 * Log an exception that wasn't thrown but made to wrap an error.
629 * @param ErrorException $e
630 * @param string $channel
631 * @param string $level
633 protected static function logError(
634 ErrorException
$e, $channel, $level = LogLevel
::ERROR
636 $catcher = self
::CAUGHT_BY_HANDLER
;
637 // The set_error_handler callback is independent from error_reporting.
638 // Filter out unwanted errors manually (e.g. when
639 // MediaWiki\suppressWarnings is active).
640 $suppressed = ( error_reporting() & $e->getSeverity() ) === 0;
641 if ( !$suppressed ) {
642 $logger = LoggerFactory
::getInstance( $channel );
645 self
::getLogMessage( $e ),
646 self
::getLogContext( $e, $catcher )
650 // Include all errors in the json log (surpressed errors will be flagged)
651 $json = self
::jsonSerializeException( $e, false, FormatJson
::ALL_OK
, $catcher );
652 if ( $json !== false ) {
653 $logger = LoggerFactory
::getInstance( "{$channel}-json" );
654 $logger->log( $level, $json, [ 'private' => true ] );
657 Hooks
::run( 'LogException', [ $e, $suppressed ] );