Move ILoadBalancer to Rdbms namespace
[mediawiki.git] / includes / exception / MWExceptionHandler.php
blobbef379eedacc614cad2502676b28670c849a6a00
1 <?php
2 /**
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
18 * @file
21 use MediaWiki\Logger\LoggerFactory;
22 use MediaWiki\MediaWikiServices;
24 /**
25 * Handler class for MWExceptions
26 * @ingroup Exception
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
32 /**
33 * @var string $reservedMemory
35 protected static $reservedMemory;
36 /**
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,
43 /**
44 * @var bool $handledFatalCallback
46 protected static $handledFatalCallback = false;
48 /**
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' );
60 /**
61 * Report an exception to the user
62 * @param Exception|Throwable $e
64 protected static function report( $e ) {
65 try {
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
70 // removed.
71 $e->report();
72 } else {
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 );
83 /**
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.
88 * @since 1.23
89 * @param Exception|Throwable $e
91 public static function rollbackMasterChangesAndLog( $e ) {
92 $services = MediaWikiServices::getInstance();
93 if ( $services->isServiceDisabled( 'DBLoadBalancerFactory' ) ) {
94 return; // T147599
97 $lbFactory = $services->getDBLoadBalancerFactory();
98 if ( $lbFactory->hasMasterChanges() ) {
99 $logger = LoggerFactory::getInstance( 'Bug56269' );
100 $logger->warning(
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:
112 * try {
113 * ...
114 * } catch ( Exception $e ) {
115 * $e->report();
116 * } catch ( Exception $e ) {
117 * echo $e->__toString();
120 * @since 1.25
121 * @param Exception|Throwable $e
123 public static function handleException( $e ) {
124 try {
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 );
139 self::report( $e );
141 // Exit value should be nonzero for the benefit of shell jobs
142 exit( 1 );
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.
153 * @since 1.25
155 * @param int $level Error level raised
156 * @param string $message
157 * @param string $file
158 * @param int $line
159 * @return bool
161 * @see logError()
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
173 // reporting)
174 switch ( $level ) {
175 case E_RECOVERABLE_ERROR:
176 $levelName = 'Error';
177 break;
178 case E_WARNING:
179 case E_CORE_WARNING:
180 case E_COMPILE_WARNING:
181 case E_USER_WARNING:
182 $levelName = 'Warning';
183 break;
184 case E_NOTICE:
185 case E_USER_NOTICE:
186 $levelName = 'Notice';
187 break;
188 case E_STRICT:
189 $levelName = 'Strict Standards';
190 break;
191 case E_DEPRECATED:
192 case E_USER_DEPRECATED:
193 $levelName = 'Deprecated';
194 break;
195 default:
196 $levelName = 'Unknown error';
197 break;
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.
205 return false;
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.
218 * @since 1.25
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
226 * feature)
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
234 // errors
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.
242 return false;
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'];
251 } else {
252 $level = 0;
253 $message = '';
257 if ( !in_array( $level, self::$fatalErrorTypes ) ) {
258 // Only interested in fatal errors, others should have been
259 // handled by MWExceptionHandler::handleError
260 return false;
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
270 $msg = <<<TXT
271 {$msg}
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.
276 TXT;
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
285 // log.
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}",
292 'code' => $level,
293 'file' => $file,
294 'line' => $line,
295 'trace' => static::redactTrace( $trace ),
297 'exception_id' => wfRandomString( 8 ),
298 'caught_by' => self::CAUGHT_BY_HANDLER
299 ] );
301 // Remember call so we don't double process via HHVM's fatal
302 // notifications and the shutdown hook behavior
303 static::$handledFatalCallback = true;
304 return false;
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
314 * @return string
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
326 * @return string
327 * @since 1.26
329 public static function prettyPrintTrace( array $trace, $pad = '' ) {
330 $text = '';
332 $level = 0;
333 foreach ( $trace as $level => $frame ) {
334 if ( isset( $frame['file'] ) && isset( $frame['line'] ) ) {
335 $text .= "{$pad}#{$level} {$frame['file']}({$frame['line']}): ";
336 } else {
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
340 // function]".
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'];
348 } else {
349 $text .= 'NO_FUNCTION_GIVEN';
352 if ( isset( $frame['args'] ) ) {
353 $text .= '(' . implode( ', ', $frame['args'] ) . ")\n";
354 } else {
355 $text .= "()\n";
359 $level = $level + 1;
360 $text .= "{$pad}#{$level} {main}";
362 return $text;
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).
372 * @since 1.22
373 * @param Exception|Throwable $e
374 * @return array
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).
386 * @since 1.26
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 );
395 }, $frame['args'] );
397 return $frame;
398 }, $trace );
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.
407 * @since 1.22
408 * @deprecated since 1.27: Exception IDs are synonymous with request IDs.
409 * @param Exception|Throwable $e
410 * @return string
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.
421 * @since 1.23
422 * @return string|false
424 public static function getURL() {
425 global $wgRequest;
426 if ( !isset( $wgRequest ) || $wgRequest instanceof FauxRequest ) {
427 return false;
429 return $wgRequest->getRequestURL();
433 * Get a message formatting the exception message and its origin.
435 * @since 1.22
436 * @param Exception|Throwable $e
437 * @return string
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
452 * @return string
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
467 * logger.
469 * @param Exception|Throwable $e
470 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
471 * @return array
473 public static function getLogContext( $e, $catcher = self::CAUGHT_BY_OTHER ) {
474 return [
475 'exception' => $e,
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
490 * @return array
491 * @since 1.26
493 public static function getStructuredExceptionData( $e, $catcher = self::CAUGHT_BY_OTHER ) {
494 global $wgLogExceptionBacktrace;
496 $data = [
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 );
523 return $data;
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
533 * request.
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):
542 * @code
544 * "id": "c41fb419",
545 * "type": "MWException",
546 * "file": "/var/www/mediawiki/includes/cache/MessageCache.php",
547 * "line": 704,
548 * "message": "Non-string key given",
549 * "url": "/wiki/Main_Page"
551 * @endcode
553 * @par Sample JSON record ($wgLogExceptionBacktrace = true):
554 * @code
556 * "id": "dc457938",
557 * "type": "MWException",
558 * "file": "/vagrant/mediawiki/includes/cache/MessageCache.php",
559 * "line": 704,
560 * "message": "Non-string key given",
561 * "url": "/wiki/Main_Page",
562 * "backtrace": [{
563 * "file": "/vagrant/mediawiki/extensions/VisualEditor/VisualEditor.hooks.php",
564 * "line": 80,
565 * "function": "get",
566 * "class": "MessageCache",
567 * "type": "->",
568 * "args": ["array"]
569 * }]
571 * @endcode
573 * @since 1.23
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 ),
585 $pretty,
586 $escaping
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.
596 * @since 1.22
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' );
603 $logger->error(
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.
621 * @since 1.25
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 );
633 $logger->error(
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 ] );