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
{
29 const CAUGHT_BY_HANDLER
= 'mwe_handler'; // error reported by this exception handler
30 const CAUGHT_BY_OTHER
= 'other'; // error reported by direct logException() call
33 * @var string $reservedMemory
35 protected static $reservedMemory;
37 * @var array $fatalErrorTypes
39 protected static $fatalErrorTypes = [
40 E_ERROR
, E_PARSE
, E_CORE_ERROR
, E_COMPILE_ERROR
, E_USER_ERROR
,
41 /* HHVM's FATAL_ERROR level */ 16777217,
44 * @var bool $handledFatalCallback
46 protected static $handledFatalCallback = false;
49 * Install handlers with PHP.
51 public static function installHandler() {
52 set_exception_handler( 'MWExceptionHandler::handleException' );
53 set_error_handler( 'MWExceptionHandler::handleError' );
55 // Reserve 16k of memory so we can report OOM fatals
56 self
::$reservedMemory = str_repeat( ' ', 16384 );
57 register_shutdown_function( 'MWExceptionHandler::handleFatalError' );
61 * Report an exception to the user
62 * @param Exception|Throwable $e
64 protected static function report( $e ) {
66 // Try and show the exception prettily, with the normal skin infrastructure
67 if ( $e instanceof MWException
) {
68 // Delegate to MWException until all subclasses are handled by
69 // MWExceptionRenderer and MWException::report() has been
73 MWExceptionRenderer
::output( $e, MWExceptionRenderer
::AS_PRETTY
);
75 } catch ( Exception
$e2 ) {
76 // Exception occurred from within exception handler
77 // Show a simpler message for the original exception,
78 // don't try to invoke report()
79 MWExceptionRenderer
::output( $e, MWExceptionRenderer
::AS_RAW
, $e2 );
84 * If there are any open database transactions, roll them back and log
85 * the stack trace of the exception that should have been caught so the
86 * transaction could be aborted properly.
89 * @param Exception|Throwable $e
91 public static function rollbackMasterChangesAndLog( $e ) {
92 $services = MediaWikiServices
::getInstance();
93 if ( $services->isServiceDisabled( 'DBLoadBalancerFactory' ) ) {
97 $lbFactory = $services->getDBLoadBalancerFactory();
98 if ( $lbFactory->hasMasterChanges() ) {
99 $logger = LoggerFactory
::getInstance( 'Bug56269' );
101 'Exception thrown with an uncommited database transaction: ' .
102 self
::getLogMessage( $e ),
103 self
::getLogContext( $e )
106 $lbFactory->rollbackMasterChanges( __METHOD__
);
110 * Exception handler which simulates the appropriate catch() handling:
114 * } catch ( Exception $e ) {
116 * } catch ( Exception $e ) {
117 * echo $e->__toString();
121 * @param Exception|Throwable $e
123 public static function handleException( $e ) {
125 // Rollback DBs to avoid transaction notices. This may fail
126 // to rollback some DB due to connection issues or exceptions.
127 // However, any sane DB driver will rollback implicitly anyway.
128 self
::rollbackMasterChangesAndLog( $e );
129 } catch ( DBError
$e2 ) {
130 // If the DB is unreacheable, rollback() will throw an error
131 // and the error report() method might need messages from the DB,
132 // which would result in an exception loop. PHP may escalate such
133 // errors to "Exception thrown without a stack frame" fatals, but
134 // it's better to be explicit here.
135 self
::logException( $e2, self
::CAUGHT_BY_HANDLER
);
138 self
::logException( $e, self
::CAUGHT_BY_HANDLER
);
141 // Exit value should be nonzero for the benefit of shell jobs
146 * Handler for set_error_handler() callback notifications.
148 * Receive a callback from the interpreter for a raised error, create an
149 * ErrorException, and log the exception to the 'error' logging
150 * channel(s). If the raised error is a fatal error type (only under HHVM)
151 * delegate to handleFatalError() instead.
155 * @param int $level Error level raised
156 * @param string $message
157 * @param string $file
163 public static function handleError(
164 $level, $message, $file = null, $line = null
166 if ( in_array( $level, self
::$fatalErrorTypes ) ) {
167 return call_user_func_array(
168 'MWExceptionHandler::handleFatalError', func_get_args()
172 // Map error constant to error name (reverse-engineer PHP error
175 case E_RECOVERABLE_ERROR
:
176 $levelName = 'Error';
180 case E_COMPILE_WARNING
:
182 $levelName = 'Warning';
186 $levelName = 'Notice';
189 $levelName = 'Strict Standards';
192 case E_USER_DEPRECATED
:
193 $levelName = 'Deprecated';
196 $levelName = 'Unknown error';
200 $e = new ErrorException( "PHP $levelName: $message", 0, $level, $file, $line );
201 self
::logError( $e, 'error' );
203 // This handler is for logging only. Return false will instruct PHP
204 // to continue regular handling.
209 * Dual purpose callback used as both a set_error_handler() callback and
210 * a registered shutdown function. Receive a callback from the interpreter
211 * for a raised error or system shutdown, check for a fatal error, and log
212 * to the 'fatal' logging channel.
214 * Special handling is included for missing class errors as they may
215 * indicate that the user needs to install 3rd-party libraries via
216 * Composer or other means.
220 * @param int $level Error level raised
221 * @param string $message Error message
222 * @param string $file File that error was raised in
223 * @param int $line Line number error was raised at
224 * @param array $context Active symbol table point of error
225 * @param array $trace Backtrace at point of error (undocumented HHVM
227 * @return bool Always returns false
229 public static function handleFatalError(
230 $level = null, $message = null, $file = null, $line = null,
231 $context = null, $trace = null
233 // Free reserved memory so that we have space to process OOM
235 self
::$reservedMemory = null;
237 if ( $level === null ) {
238 // Called as a shutdown handler, get data from error_get_last()
239 if ( static::$handledFatalCallback ) {
240 // Already called once (probably as an error handler callback
241 // under HHVM) so don't log again.
245 $lastError = error_get_last();
246 if ( $lastError !== null ) {
247 $level = $lastError['type'];
248 $message = $lastError['message'];
249 $file = $lastError['file'];
250 $line = $lastError['line'];
257 if ( !in_array( $level, self
::$fatalErrorTypes ) ) {
258 // Only interested in fatal errors, others should have been
259 // handled by MWExceptionHandler::handleError
263 $msg = "[{exception_id}] PHP Fatal Error: {$message}";
265 // Look at message to see if this is a class not found failure
266 // HHVM: Class undefined: foo
267 // PHP5: Class 'foo' not found
268 if ( preg_match( "/Class (undefined: \w+|'\w+' not found)/", $msg ) ) {
269 // @codingStandardsIgnoreStart Generic.Files.LineLength.TooLong
273 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.
275 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.
277 // @codingStandardsIgnoreEnd
280 // We can't just create an exception and log it as it is likely that
281 // the interpreter has unwound the stack already. If that is true the
282 // stacktrace we would get would be functionally empty. If however we
283 // have been called as an error handler callback *and* HHVM is in use
284 // we will have been provided with a useful stacktrace that we can
286 $trace = $trace ?
: debug_backtrace();
287 $logger = LoggerFactory
::getInstance( 'fatal' );
288 $logger->error( $msg, [
289 'fatal_exception' => [
290 'class' => 'ErrorException',
291 'message' => "PHP Fatal Error: {$message}",
295 'trace' => static::redactTrace( $trace ),
297 'exception_id' => wfRandomString( 8 ),
298 'caught_by' => self
::CAUGHT_BY_HANDLER
301 // Remember call so we don't double process via HHVM's fatal
302 // notifications and the shutdown hook behavior
303 static::$handledFatalCallback = true;
308 * Generate a string representation of an exception's stack trace
310 * Like Exception::getTraceAsString, but replaces argument values with
311 * argument type or class name.
313 * @param Exception|Throwable $e
315 * @see prettyPrintTrace()
317 public static function getRedactedTraceAsString( $e ) {
318 return self
::prettyPrintTrace( self
::getRedactedTrace( $e ) );
322 * Generate a string representation of a stacktrace.
324 * @param array $trace
325 * @param string $pad Constant padding to add to each line of trace
329 public static function prettyPrintTrace( array $trace, $pad = '' ) {
333 foreach ( $trace as $level => $frame ) {
334 if ( isset( $frame['file'] ) && isset( $frame['line'] ) ) {
335 $text .= "{$pad}#{$level} {$frame['file']}({$frame['line']}): ";
337 // 'file' and 'line' are unset for calls via call_user_func
338 // (bug 55634) This matches behaviour of
339 // Exception::getTraceAsString to instead display "[internal
341 $text .= "{$pad}#{$level} [internal function]: ";
344 if ( isset( $frame['class'] ) && isset( $frame['type'] ) && isset( $frame['function'] ) ) {
345 $text .= $frame['class'] . $frame['type'] . $frame['function'];
346 } elseif ( isset( $frame['function'] ) ) {
347 $text .= $frame['function'];
349 $text .= 'NO_FUNCTION_GIVEN';
352 if ( isset( $frame['args'] ) ) {
353 $text .= '(' . implode( ', ', $frame['args'] ) . ")\n";
360 $text .= "{$pad}#{$level} {main}";
366 * Return a copy of an exception's backtrace as an array.
368 * Like Exception::getTrace, but replaces each element in each frame's
369 * argument array with the name of its class (if the element is an object)
370 * or its type (if the element is a PHP primitive).
373 * @param Exception|Throwable $e
376 public static function getRedactedTrace( $e ) {
377 return static::redactTrace( $e->getTrace() );
381 * Redact a stacktrace generated by Exception::getTrace(),
382 * debug_backtrace() or similar means. Replaces each element in each
383 * frame's argument array with the name of its class (if the element is an
384 * object) or its type (if the element is a PHP primitive).
387 * @param array $trace Stacktrace
388 * @return array Stacktrace with arugment values converted to data types
390 public static function redactTrace( array $trace ) {
391 return array_map( function ( $frame ) {
392 if ( isset( $frame['args'] ) ) {
393 $frame['args'] = array_map( function ( $arg ) {
394 return is_object( $arg ) ?
get_class( $arg ) : gettype( $arg );
402 * Get the ID for this exception.
404 * The ID is saved so that one can match the one output to the user (when
405 * $wgShowExceptionDetails is set to false), to the entry in the debug log.
408 * @deprecated since 1.27: Exception IDs are synonymous with request IDs.
409 * @param Exception|Throwable $e
412 public static function getLogId( $e ) {
413 wfDeprecated( __METHOD__
, '1.27' );
414 return WebRequest
::getRequestId();
418 * If the exception occurred in the course of responding to a request,
419 * returns the requested URL. Otherwise, returns false.
422 * @return string|false
424 public static function getURL() {
426 if ( !isset( $wgRequest ) ||
$wgRequest instanceof FauxRequest
) {
429 return $wgRequest->getRequestURL();
433 * Get a message formatting the exception message and its origin.
436 * @param Exception|Throwable $e
439 public static function getLogMessage( $e ) {
440 $id = WebRequest
::getRequestId();
441 $type = get_class( $e );
442 $file = $e->getFile();
443 $line = $e->getLine();
444 $message = $e->getMessage();
445 $url = self
::getURL() ?
: '[no req]';
447 return "[$id] $url $type from line $line of $file: $message";
451 * @param Exception|Throwable $e
454 public static function getPublicLogMessage( $e ) {
455 $reqId = WebRequest
::getRequestId();
456 $type = get_class( $e );
457 return '[' . $reqId . '] '
458 . gmdate( 'Y-m-d H:i:s' ) . ': '
459 . 'Fatal exception of type "' . $type . '"';
463 * Get a PSR-3 log event context from an Exception.
465 * Creates a structured array containing information about the provided
466 * exception that can be used to augment a log message sent to a PSR-3
469 * @param Exception|Throwable $e
470 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
473 public static function getLogContext( $e, $catcher = self
::CAUGHT_BY_OTHER
) {
476 'exception_id' => WebRequest
::getRequestId(),
477 'caught_by' => $catcher
482 * Get a structured representation of an Exception.
484 * Returns an array of structured data (class, message, code, file,
485 * backtrace) derived from the given exception. The backtrace information
486 * will be redacted as per getRedactedTraceAsArray().
488 * @param Exception|Throwable $e
489 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
493 public static function getStructuredExceptionData( $e, $catcher = self
::CAUGHT_BY_OTHER
) {
494 global $wgLogExceptionBacktrace;
497 'id' => WebRequest
::getRequestId(),
498 'type' => get_class( $e ),
499 'file' => $e->getFile(),
500 'line' => $e->getLine(),
501 'message' => $e->getMessage(),
502 'code' => $e->getCode(),
503 'url' => self
::getURL() ?
: null,
504 'caught_by' => $catcher
507 if ( $e instanceof ErrorException
&&
508 ( error_reporting() & $e->getSeverity() ) === 0
510 // Flag surpressed errors
511 $data['suppressed'] = true;
514 if ( $wgLogExceptionBacktrace ) {
515 $data['backtrace'] = self
::getRedactedTrace( $e );
518 $previous = $e->getPrevious();
519 if ( $previous !== null ) {
520 $data['previous'] = self
::getStructuredExceptionData( $previous, $catcher );
527 * Serialize an Exception object to JSON.
529 * The JSON object will have keys 'id', 'file', 'line', 'message', and
530 * 'url'. These keys map to string values, with the exception of 'line',
531 * which is a number, and 'url', which may be either a string URL or or
532 * null if the exception did not occur in the context of serving a web
535 * If $wgLogExceptionBacktrace is true, it will also have a 'backtrace'
536 * key, mapped to the array return value of Exception::getTrace, but with
537 * each element in each frame's "args" array (if set) replaced with the
538 * argument's class name (if the argument is an object) or type name (if
539 * the argument is a PHP primitive).
541 * @par Sample JSON record ($wgLogExceptionBacktrace = false):
545 * "type": "MWException",
546 * "file": "/var/www/mediawiki/includes/cache/MessageCache.php",
548 * "message": "Non-string key given",
549 * "url": "/wiki/Main_Page"
553 * @par Sample JSON record ($wgLogExceptionBacktrace = true):
557 * "type": "MWException",
558 * "file": "/vagrant/mediawiki/includes/cache/MessageCache.php",
560 * "message": "Non-string key given",
561 * "url": "/wiki/Main_Page",
563 * "file": "/vagrant/mediawiki/extensions/VisualEditor/VisualEditor.hooks.php",
566 * "class": "MessageCache",
574 * @param Exception|Throwable $e
575 * @param bool $pretty Add non-significant whitespace to improve readability (default: false).
576 * @param int $escaping Bitfield consisting of FormatJson::.*_OK class constants.
577 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
578 * @return string|false JSON string if successful; false upon failure
580 public static function jsonSerializeException(
581 $e, $pretty = false, $escaping = 0, $catcher = self
::CAUGHT_BY_OTHER
583 return FormatJson
::encode(
584 self
::getStructuredExceptionData( $e, $catcher ),
591 * Log an exception to the exception log (if enabled).
593 * This method must not assume the exception is an MWException,
594 * it is also used to handle PHP exceptions or exceptions from other libraries.
597 * @param Exception|Throwable $e
598 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
600 public static function logException( $e, $catcher = self
::CAUGHT_BY_OTHER
) {
601 if ( !( $e instanceof MWException
) ||
$e->isLoggable() ) {
602 $logger = LoggerFactory
::getInstance( 'exception' );
604 self
::getLogMessage( $e ),
605 self
::getLogContext( $e, $catcher )
608 $json = self
::jsonSerializeException( $e, false, FormatJson
::ALL_OK
, $catcher );
609 if ( $json !== false ) {
610 $logger = LoggerFactory
::getInstance( 'exception-json' );
611 $logger->error( $json, [ 'private' => true ] );
614 Hooks
::run( 'LogException', [ $e, false ] );
619 * Log an exception that wasn't thrown but made to wrap an error.
622 * @param ErrorException $e
623 * @param string $channel
625 protected static function logError( ErrorException
$e, $channel ) {
626 $catcher = self
::CAUGHT_BY_HANDLER
;
627 // The set_error_handler callback is independent from error_reporting.
628 // Filter out unwanted errors manually (e.g. when
629 // MediaWiki\suppressWarnings is active).
630 $suppressed = ( error_reporting() & $e->getSeverity() ) === 0;
631 if ( !$suppressed ) {
632 $logger = LoggerFactory
::getInstance( $channel );
634 self
::getLogMessage( $e ),
635 self
::getLogContext( $e, $catcher )
639 // Include all errors in the json log (surpressed errors will be flagged)
640 $json = self
::jsonSerializeException( $e, false, FormatJson
::ALL_OK
, $catcher );
641 if ( $json !== false ) {
642 $logger = LoggerFactory
::getInstance( "{$channel}-json" );
643 $logger->error( $json, [ 'private' => true ] );
646 Hooks
::run( 'LogException', [ $e, $suppressed ] );