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
22 * Handler class for MWExceptions
25 class MWExceptionHandler
{
27 protected static $reservedMemory;
28 protected static $fatalErrorTypes = array(
29 E_ERROR
, E_PARSE
, E_CORE_ERROR
, E_COMPILE_ERROR
, E_USER_ERROR
,
30 /* HHVM's FATAL_ERROR level */ 16777217,
34 * Install handlers with PHP.
36 public static function installHandler() {
37 set_exception_handler( array( 'MWExceptionHandler', 'handleException' ) );
38 set_error_handler( array( 'MWExceptionHandler', 'handleError' ) );
40 // Reserve 16k of memory so we can report OOM fatals
41 self
::$reservedMemory = str_repeat( ' ', 16384 );
42 register_shutdown_function(
43 array( 'MWExceptionHandler', 'handleFatalError' )
48 * Report an exception to the user
51 protected static function report( Exception
$e ) {
52 global $wgShowExceptionDetails;
54 $cmdLine = MWException
::isCommandLine();
56 if ( $e instanceof MWException
) {
58 // Try and show the exception prettily, with the normal skin infrastructure
60 } catch ( Exception
$e2 ) {
61 // Exception occurred from within exception handler
62 // Show a simpler message for the original exception,
63 // don't try to invoke report()
64 $message = "MediaWiki internal error.\n\n";
66 if ( $wgShowExceptionDetails ) {
67 $message .= 'Original exception: ' . self
::getLogMessage( $e ) .
68 "\nBacktrace:\n" . self
::getRedactedTraceAsString( $e ) .
69 "\n\nException caught inside exception handler: " . self
::getLogMessage( $e2 ) .
70 "\nBacktrace:\n" . self
::getRedactedTraceAsString( $e2 );
72 $message .= "Exception caught inside exception handler.\n\n" .
73 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
74 "to show detailed debugging information.";
80 self
::printError( $message );
82 echo nl2br( htmlspecialchars( $message ) ) . "\n";
86 $message = "Exception encountered, of type \"" . get_class( $e ) . "\"";
88 if ( $wgShowExceptionDetails ) {
89 $message .= "\n" . MWExceptionHandler
::getLogMessage( $e ) . "\nBacktrace:\n" .
90 self
::getRedactedTraceAsString( $e ) . "\n";
94 self
::printError( $message );
96 echo nl2br( htmlspecialchars( $message ) ) . "\n";
103 * Print a message, if possible to STDERR.
104 * Use this in command line mode only (see isCommandLine)
106 * @param string $message Failure text
108 public static function printError( $message ) {
109 # NOTE: STDERR may not be available, especially if php-cgi is used from the
110 # command line (bug #15602). Try to produce meaningful output anyway. Using
111 # echo may corrupt output to STDOUT though.
112 if ( defined( 'STDERR' ) ) {
113 fwrite( STDERR
, $message );
120 * If there are any open database transactions, roll them back and log
121 * the stack trace of the exception that should have been caught so the
122 * transaction could be aborted properly.
125 * @param Exception $e
127 public static function rollbackMasterChangesAndLog( Exception
$e ) {
128 $factory = wfGetLBFactory();
129 if ( $factory->hasMasterChanges() ) {
130 wfDebugLog( 'Bug56269',
131 'Exception thrown with an uncommited database transaction: ' .
132 MWExceptionHandler
::getLogMessage( $e ) . "\n" .
133 $e->getTraceAsString()
135 $factory->rollbackMasterChanges();
140 * Exception handler which simulates the appropriate catch() handling:
144 * } catch ( Exception $e ) {
146 * } catch ( Exception $e ) {
147 * echo $e->__toString();
151 * @param Exception $e
153 public static function handleException( Exception
$e ) {
155 // Rollback DBs to avoid transaction notices. This may fail
156 // to rollback some DB due to connection issues or exceptions.
157 // However, any sane DB driver will rollback implicitly anyway.
158 self
::rollbackMasterChangesAndLog( $e );
159 } catch ( DBError
$e2 ) {
160 // If the DB is unreacheable, rollback() will throw an error
161 // and the error report() method might need messages from the DB,
162 // which would result in an exception loop. PHP may escalate such
163 // errors to "Exception thrown without a stack frame" fatals, but
164 // it's better to be explicit here.
165 self
::logException( $e2 );
168 self
::logException( $e );
171 // Exit value should be nonzero for the benefit of shell jobs
177 * @param int $level Error level raised
178 * @param string $message
179 * @param string $file
182 public static function handleError( $level, $message, $file = null, $line = null ) {
183 // Map error constant to error name (reverse-engineer PHP error reporting)
188 case E_COMPILE_ERROR
:
190 case E_RECOVERABLE_ERROR
:
192 $levelName = 'Error';
197 case E_COMPILE_WARNING
:
199 $levelName = 'Warning';
203 $levelName = 'Notice';
206 $levelName = 'Strict Standards';
209 case E_USER_DEPRECATED
:
210 $levelName = 'Deprecated';
212 case /* HHVM's FATAL_ERROR */ 16777217:
213 $levelName = 'Fatal';
217 $levelName = 'Unknown error';
221 $e = new ErrorException( "PHP $levelName: $message", 0, $level, $file, $line );
222 self
::logError( $e, $channel );
224 // This handler is for logging only. Return false will instruct PHP
225 // to continue regular handling.
231 * Look for a fatal error as the cause of the request termination and log
234 * Special handling is included for missing class errors as they may
235 * indicate that the user needs to install 3rd-party libraries via
236 * Composer or other means.
240 public static function handleFatalError() {
241 self
::$reservedMemory = null;
242 $lastError = error_get_last();
245 isset( $lastError['type'] ) &&
246 in_array( $lastError['type'], self
::$fatalErrorTypes )
248 $msg = "Fatal Error: {$lastError['message']}";
249 // HHVM: Class undefined: foo
250 // PHP5: Class 'foo' not found
251 if ( preg_match( "/Class (undefined: \w+|'\w+' not found)/",
252 $lastError['message']
254 // @codingStandardsIgnoreStart Generic.Files.LineLength.TooLong
258 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.
260 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.
262 // @codingStandardsIgnoreEnd
264 $e = new ErrorException( $msg, 0, $lastError['type'] );
265 self
::logError( $e, 'fatal' );
270 * Generate a string representation of an exception's stack trace
272 * Like Exception::getTraceAsString, but replaces argument values with
273 * argument type or class name.
275 * @param Exception $e
278 public static function getRedactedTraceAsString( Exception
$e ) {
281 foreach ( self
::getRedactedTrace( $e ) as $level => $frame ) {
282 if ( isset( $frame['file'] ) && isset( $frame['line'] ) ) {
283 $text .= "#{$level} {$frame['file']}({$frame['line']}): ";
285 // 'file' and 'line' are unset for calls via call_user_func (bug 55634)
286 // This matches behaviour of Exception::getTraceAsString to instead
287 // display "[internal function]".
288 $text .= "#{$level} [internal function]: ";
291 if ( isset( $frame['class'] ) ) {
292 $text .= $frame['class'] . $frame['type'] . $frame['function'];
294 $text .= $frame['function'];
297 if ( isset( $frame['args'] ) ) {
298 $text .= '(' . implode( ', ', $frame['args'] ) . ")\n";
305 $text .= "#{$level} {main}";
311 * Return a copy of an exception's backtrace as an array.
313 * Like Exception::getTrace, but replaces each element in each frame's
314 * argument array with the name of its class (if the element is an object)
315 * or its type (if the element is a PHP primitive).
318 * @param Exception $e
321 public static function getRedactedTrace( Exception
$e ) {
322 return array_map( function ( $frame ) {
323 if ( isset( $frame['args'] ) ) {
324 $frame['args'] = array_map( function ( $arg ) {
325 return is_object( $arg ) ?
get_class( $arg ) : gettype( $arg );
333 * Get the ID for this exception.
335 * The ID is saved so that one can match the one output to the user (when
336 * $wgShowExceptionDetails is set to false), to the entry in the debug log.
339 * @param Exception $e
342 public static function getLogId( Exception
$e ) {
343 if ( !isset( $e->_mwLogId
) ) {
344 $e->_mwLogId
= wfRandomString( 8 );
350 * If the exception occurred in the course of responding to a request,
351 * returns the requested URL. Otherwise, returns false.
354 * @return string|false
356 public static function getURL() {
358 if ( !isset( $wgRequest ) ||
$wgRequest instanceof FauxRequest
) {
361 return $wgRequest->getRequestURL();
365 * Get a message formatting the exception message and its origin.
368 * @param Exception $e
371 public static function getLogMessage( Exception
$e ) {
372 $id = self
::getLogId( $e );
373 $type = get_class( $e );
374 $file = $e->getFile();
375 $line = $e->getLine();
376 $message = $e->getMessage();
377 $url = self
::getURL() ?
: '[no req]';
379 return "[$id] $url $type from line $line of $file: $message";
383 * Serialize an Exception object to JSON.
385 * The JSON object will have keys 'id', 'file', 'line', 'message', and
386 * 'url'. These keys map to string values, with the exception of 'line',
387 * which is a number, and 'url', which may be either a string URL or or
388 * null if the exception did not occur in the context of serving a web
391 * If $wgLogExceptionBacktrace is true, it will also have a 'backtrace'
392 * key, mapped to the array return value of Exception::getTrace, but with
393 * each element in each frame's "args" array (if set) replaced with the
394 * argument's class name (if the argument is an object) or type name (if
395 * the argument is a PHP primitive).
397 * @par Sample JSON record ($wgLogExceptionBacktrace = false):
401 * "type": "MWException",
402 * "file": "/var/www/mediawiki/includes/cache/MessageCache.php",
404 * "message": "Non-string key given",
405 * "url": "/wiki/Main_Page"
409 * @par Sample JSON record ($wgLogExceptionBacktrace = true):
413 * "type": "MWException",
414 * "file": "/vagrant/mediawiki/includes/cache/MessageCache.php",
416 * "message": "Non-string key given",
417 * "url": "/wiki/Main_Page",
419 * "file": "/vagrant/mediawiki/extensions/VisualEditor/VisualEditor.hooks.php",
422 * "class": "MessageCache",
430 * @param Exception $e
431 * @param bool $pretty Add non-significant whitespace to improve readability (default: false).
432 * @param int $escaping Bitfield consisting of FormatJson::.*_OK class constants.
433 * @return string|false JSON string if successful; false upon failure
435 public static function jsonSerializeException( Exception
$e, $pretty = false, $escaping = 0 ) {
436 global $wgLogExceptionBacktrace;
438 $exceptionData = array(
439 'id' => self
::getLogId( $e ),
440 'type' => get_class( $e ),
441 'file' => $e->getFile(),
442 'line' => $e->getLine(),
443 'message' => $e->getMessage(),
446 if ( $e instanceof ErrorException
&& ( error_reporting() & $e->getSeverity() ) === 0 ) {
447 // Flag surpressed errors
448 $exceptionData['suppressed'] = true;
451 // Because MediaWiki is first and foremost a web application, we set a
452 // 'url' key unconditionally, but set it to null if the exception does
453 // not occur in the context of a web request, as a way of making that
454 // fact visible and explicit.
455 $exceptionData['url'] = self
::getURL() ?
: null;
457 if ( $wgLogExceptionBacktrace ) {
458 // Argument values may not be serializable, so redact them.
459 $exceptionData['backtrace'] = self
::getRedactedTrace( $e );
462 return FormatJson
::encode( $exceptionData, $pretty, $escaping );
466 * Log an exception to the exception log (if enabled).
468 * This method must not assume the exception is an MWException,
469 * it is also used to handle PHP exceptions or exceptions from other libraries.
472 * @param Exception $e
474 public static function logException( Exception
$e ) {
475 global $wgLogExceptionBacktrace;
477 if ( !( $e instanceof MWException
) ||
$e->isLoggable() ) {
478 $log = self
::getLogMessage( $e );
479 if ( $wgLogExceptionBacktrace ) {
480 wfDebugLog( 'exception', $log . "\n" . $e->getTraceAsString() );
482 wfDebugLog( 'exception', $log );
485 $json = self
::jsonSerializeException( $e, false, FormatJson
::ALL_OK
);
486 if ( $json !== false ) {
487 wfDebugLog( 'exception-json', $json, 'private' );
493 * Log an exception that wasn't thrown but made to wrap an error.
496 * @param ErrorException $e
497 * @param string $channel
499 protected static function logError( ErrorException
$e, $channel ) {
500 global $wgLogExceptionBacktrace;
502 // The set_error_handler callback is independent from error_reporting.
503 // Filter out unwanted errors manually (e.g. when wfSuppressWarnings is active).
504 if ( ( error_reporting() & $e->getSeverity() ) !== 0 ) {
505 $log = self
::getLogMessage( $e );
506 if ( $wgLogExceptionBacktrace ) {
507 wfDebugLog( $channel, $log . "\n" . $e->getTraceAsString() );
509 wfDebugLog( $channel, $log );
513 // Include all errors in the json log (surpressed errors will be flagged)
514 $json = self
::jsonSerializeException( $e, false, FormatJson
::ALL_OK
);
515 if ( $json !== false ) {
516 wfDebugLog( "$channel-json", $json, 'private' );