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
;
24 * Handler class for MWExceptions
27 class MWExceptionHandler
{
29 protected static $reservedMemory;
30 protected static $fatalErrorTypes = array(
31 E_ERROR
, E_PARSE
, E_CORE_ERROR
, E_COMPILE_ERROR
, E_USER_ERROR
,
32 /* HHVM's FATAL_ERROR level */ 16777217,
36 * Install handlers with PHP.
38 public static function installHandler() {
39 set_exception_handler( array( 'MWExceptionHandler', 'handleException' ) );
40 set_error_handler( array( 'MWExceptionHandler', 'handleError' ) );
42 // Reserve 16k of memory so we can report OOM fatals
43 self
::$reservedMemory = str_repeat( ' ', 16384 );
44 register_shutdown_function(
45 array( 'MWExceptionHandler', 'handleFatalError' )
50 * Report an exception to the user
53 protected static function report( Exception
$e ) {
54 global $wgShowExceptionDetails;
56 $cmdLine = MWException
::isCommandLine();
58 if ( $e instanceof MWException
) {
60 // Try and show the exception prettily, with the normal skin infrastructure
62 } catch ( Exception
$e2 ) {
63 // Exception occurred from within exception handler
64 // Show a simpler message for the original exception,
65 // don't try to invoke report()
66 $message = "MediaWiki internal error.\n\n";
68 if ( $wgShowExceptionDetails ) {
69 $message .= 'Original exception: ' . self
::getLogMessage( $e ) .
70 "\nBacktrace:\n" . self
::getRedactedTraceAsString( $e ) .
71 "\n\nException caught inside exception handler: " . self
::getLogMessage( $e2 ) .
72 "\nBacktrace:\n" . self
::getRedactedTraceAsString( $e2 );
74 $message .= "Exception caught inside exception handler.\n\n" .
75 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
76 "to show detailed debugging information.";
82 self
::printError( $message );
84 echo nl2br( htmlspecialchars( $message ) ) . "\n";
88 $message = "Exception encountered, of type \"" . get_class( $e ) . "\"";
90 if ( $wgShowExceptionDetails ) {
91 $message .= "\n" . self
::getLogMessage( $e ) . "\nBacktrace:\n" .
92 self
::getRedactedTraceAsString( $e ) . "\n";
96 self
::printError( $message );
98 echo nl2br( htmlspecialchars( $message ) ) . "\n";
105 * Print a message, if possible to STDERR.
106 * Use this in command line mode only (see isCommandLine)
108 * @param string $message Failure text
110 public static function printError( $message ) {
111 # NOTE: STDERR may not be available, especially if php-cgi is used from the
112 # command line (bug #15602). Try to produce meaningful output anyway. Using
113 # echo may corrupt output to STDOUT though.
114 if ( defined( 'STDERR' ) ) {
115 fwrite( STDERR
, $message );
122 * If there are any open database transactions, roll them back and log
123 * the stack trace of the exception that should have been caught so the
124 * transaction could be aborted properly.
127 * @param Exception $e
129 public static function rollbackMasterChangesAndLog( Exception
$e ) {
130 $factory = wfGetLBFactory();
131 if ( $factory->hasMasterChanges() ) {
132 $logger = LoggerFactory
::getInstance( 'Bug56269' );
134 'Exception thrown with an uncommited database transaction: ' .
135 self
::getLogMessage( $e ),
136 self
::getLogContext( $e )
138 $factory->rollbackMasterChanges();
143 * Exception handler which simulates the appropriate catch() handling:
147 * } catch ( Exception $e ) {
149 * } catch ( Exception $e ) {
150 * echo $e->__toString();
154 * @param Exception $e
156 public static function handleException( Exception
$e ) {
158 // Rollback DBs to avoid transaction notices. This may fail
159 // to rollback some DB due to connection issues or exceptions.
160 // However, any sane DB driver will rollback implicitly anyway.
161 self
::rollbackMasterChangesAndLog( $e );
162 } catch ( DBError
$e2 ) {
163 // If the DB is unreacheable, rollback() will throw an error
164 // and the error report() method might need messages from the DB,
165 // which would result in an exception loop. PHP may escalate such
166 // errors to "Exception thrown without a stack frame" fatals, but
167 // it's better to be explicit here.
168 self
::logException( $e2 );
171 self
::logException( $e );
174 // Exit value should be nonzero for the benefit of shell jobs
180 * @param int $level Error level raised
181 * @param string $message
182 * @param string $file
185 public static function handleError( $level, $message, $file = null, $line = null ) {
186 // Map error constant to error name (reverse-engineer PHP error reporting)
191 case E_COMPILE_ERROR
:
193 case E_RECOVERABLE_ERROR
:
195 $levelName = 'Error';
200 case E_COMPILE_WARNING
:
202 $levelName = 'Warning';
206 $levelName = 'Notice';
209 $levelName = 'Strict Standards';
212 case E_USER_DEPRECATED
:
213 $levelName = 'Deprecated';
215 case /* HHVM's FATAL_ERROR */ 16777217:
216 $levelName = 'Fatal';
220 $levelName = 'Unknown error';
224 $e = new ErrorException( "PHP $levelName: $message", 0, $level, $file, $line );
225 self
::logError( $e, $channel );
227 // This handler is for logging only. Return false will instruct PHP
228 // to continue regular handling.
234 * Look for a fatal error as the cause of the request termination and log
237 * Special handling is included for missing class errors as they may
238 * indicate that the user needs to install 3rd-party libraries via
239 * Composer or other means.
243 public static function handleFatalError() {
244 self
::$reservedMemory = null;
245 $lastError = error_get_last();
248 isset( $lastError['type'] ) &&
249 in_array( $lastError['type'], self
::$fatalErrorTypes )
251 $msg = "Fatal Error: {$lastError['message']}";
252 // HHVM: Class undefined: foo
253 // PHP5: Class 'foo' not found
254 if ( preg_match( "/Class (undefined: \w+|'\w+' not found)/",
255 $lastError['message']
257 // @codingStandardsIgnoreStart Generic.Files.LineLength.TooLong
261 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.
263 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.
265 // @codingStandardsIgnoreEnd
267 $e = new ErrorException( $msg, 0, $lastError['type'] );
268 self
::logError( $e, 'fatal' );
273 * Generate a string representation of an exception's stack trace
275 * Like Exception::getTraceAsString, but replaces argument values with
276 * argument type or class name.
278 * @param Exception $e
281 public static function getRedactedTraceAsString( Exception
$e ) {
282 return self
::prettyPrintRedactedTrace(
283 self
::getRedactedTrace( $e )
288 * Generate a string representation of a structured stack trace generated
289 * by getRedactedTrace().
291 * @param array $trace
295 public static function prettyPrintRedactedTrace( array $trace ) {
298 foreach ( $trace as $level => $frame ) {
299 if ( isset( $frame['file'] ) && isset( $frame['line'] ) ) {
300 $text .= "#{$level} {$frame['file']}({$frame['line']}): ";
302 // 'file' and 'line' are unset for calls via call_user_func (bug 55634)
303 // This matches behaviour of Exception::getTraceAsString to instead
304 // display "[internal function]".
305 $text .= "#{$level} [internal function]: ";
308 if ( isset( $frame['class'] ) ) {
309 $text .= $frame['class'] . $frame['type'] . $frame['function'];
311 $text .= $frame['function'];
314 if ( isset( $frame['args'] ) ) {
315 $text .= '(' . implode( ', ', $frame['args'] ) . ")\n";
322 $text .= "#{$level} {main}";
328 * Return a copy of an exception's backtrace as an array.
330 * Like Exception::getTrace, but replaces each element in each frame's
331 * argument array with the name of its class (if the element is an object)
332 * or its type (if the element is a PHP primitive).
335 * @param Exception $e
338 public static function getRedactedTrace( Exception
$e ) {
339 return array_map( function ( $frame ) {
340 if ( isset( $frame['args'] ) ) {
341 $frame['args'] = array_map( function ( $arg ) {
342 return is_object( $arg ) ?
get_class( $arg ) : gettype( $arg );
350 * Get the ID for this exception.
352 * The ID is saved so that one can match the one output to the user (when
353 * $wgShowExceptionDetails is set to false), to the entry in the debug log.
356 * @param Exception $e
359 public static function getLogId( Exception
$e ) {
360 if ( !isset( $e->_mwLogId
) ) {
361 $e->_mwLogId
= wfRandomString( 8 );
367 * If the exception occurred in the course of responding to a request,
368 * returns the requested URL. Otherwise, returns false.
371 * @return string|false
373 public static function getURL() {
375 if ( !isset( $wgRequest ) ||
$wgRequest instanceof FauxRequest
) {
378 return $wgRequest->getRequestURL();
382 * Get a message formatting the exception message and its origin.
385 * @param Exception $e
388 public static function getLogMessage( Exception
$e ) {
389 $id = self
::getLogId( $e );
390 $type = get_class( $e );
391 $file = $e->getFile();
392 $line = $e->getLine();
393 $message = $e->getMessage();
394 $url = self
::getURL() ?
: '[no req]';
396 return "[$id] $url $type from line $line of $file: $message";
400 * Get a PSR-3 log event context from an Exception.
402 * Creates a structured array containing information about the provided
403 * exception that can be used to augment a log message sent to a PSR-3
406 * @param Exception $e
409 public static function getLogContext( Exception
$e ) {
416 * Get a structured representation of an Exception.
418 * Returns an array of structured data (class, message, code, file,
419 * backtrace) derived from the given exception. The backtrace information
420 * will be redacted as per getRedactedTraceAsArray().
422 * @param Exception $e
426 public static function getStructuredExceptionData( Exception
$e ) {
427 global $wgLogExceptionBacktrace;
429 'id' => self
::getLogId( $e ),
430 'type' => get_class( $e ),
431 'file' => $e->getFile(),
432 'line' => $e->getLine(),
433 'message' => $e->getMessage(),
434 'code' => $e->getCode(),
435 'url' => self
::getURL() ?
: null,
438 if ( $e instanceof ErrorException
&&
439 ( error_reporting() & $e->getSeverity() ) === 0
441 // Flag surpressed errors
442 $data['suppressed'] = true;
445 if ( $wgLogExceptionBacktrace ) {
446 $data['backtrace'] = self
::getRedactedTrace( $e );
449 $previous = $e->getPrevious();
450 if ( $previous !== null ) {
451 $data['previous'] = self
::getStructuredExceptionData( $previous );
458 * Serialize an Exception object to JSON.
460 * The JSON object will have keys 'id', 'file', 'line', 'message', and
461 * 'url'. These keys map to string values, with the exception of 'line',
462 * which is a number, and 'url', which may be either a string URL or or
463 * null if the exception did not occur in the context of serving a web
466 * If $wgLogExceptionBacktrace is true, it will also have a 'backtrace'
467 * key, mapped to the array return value of Exception::getTrace, but with
468 * each element in each frame's "args" array (if set) replaced with the
469 * argument's class name (if the argument is an object) or type name (if
470 * the argument is a PHP primitive).
472 * @par Sample JSON record ($wgLogExceptionBacktrace = false):
476 * "type": "MWException",
477 * "file": "/var/www/mediawiki/includes/cache/MessageCache.php",
479 * "message": "Non-string key given",
480 * "url": "/wiki/Main_Page"
484 * @par Sample JSON record ($wgLogExceptionBacktrace = true):
488 * "type": "MWException",
489 * "file": "/vagrant/mediawiki/includes/cache/MessageCache.php",
491 * "message": "Non-string key given",
492 * "url": "/wiki/Main_Page",
494 * "file": "/vagrant/mediawiki/extensions/VisualEditor/VisualEditor.hooks.php",
497 * "class": "MessageCache",
505 * @param Exception $e
506 * @param bool $pretty Add non-significant whitespace to improve readability (default: false).
507 * @param int $escaping Bitfield consisting of FormatJson::.*_OK class constants.
508 * @return string|false JSON string if successful; false upon failure
510 public static function jsonSerializeException( Exception
$e, $pretty = false, $escaping = 0 ) {
511 $data = self
::getStructuredExceptionData( $e );
512 return FormatJson
::encode( $data, $pretty, $escaping );
516 * Log an exception to the exception log (if enabled).
518 * This method must not assume the exception is an MWException,
519 * it is also used to handle PHP exceptions or exceptions from other libraries.
522 * @param Exception $e
524 public static function logException( Exception
$e ) {
525 if ( !( $e instanceof MWException
) ||
$e->isLoggable() ) {
526 $logger = LoggerFactory
::getInstance( 'exception' );
528 self
::getLogMessage( $e ),
529 self
::getLogContext( $e )
532 $json = self
::jsonSerializeException( $e, false, FormatJson
::ALL_OK
);
533 if ( $json !== false ) {
534 $logger = LoggerFactory
::getInstance( 'exception-json' );
535 $logger->error( $json, array( 'private' => true ) );
538 Hooks
::run( 'LogException', array( $e, false ) );
543 * Log an exception that wasn't thrown but made to wrap an error.
546 * @param ErrorException $e
547 * @param string $channel
549 protected static function logError( ErrorException
$e, $channel ) {
550 // The set_error_handler callback is independent from error_reporting.
551 // Filter out unwanted errors manually (e.g. when MediaWiki\suppressWarnings is active).
552 $suppressed = ( error_reporting() & $e->getSeverity() ) === 0;
553 if ( !$suppressed ) {
554 $logger = LoggerFactory
::getInstance( $channel );
556 self
::getLogMessage( $e ),
557 self
::getLogContext( $e )
561 // Include all errors in the json log (surpressed errors will be flagged)
562 $json = self
::jsonSerializeException( $e, false, FormatJson
::ALL_OK
);
563 if ( $json !== false ) {
564 $logger = LoggerFactory
::getInstance( "{$channel}-json" );
565 $logger->error( $json, array( 'private' => true ) );
568 Hooks
::run( 'LogException', array( $e, $suppressed ) );