MediaWiki fundraising/REL1_35
MWExceptionHandler.php
Go to the documentation of this file.
1<?php
23use Psr\Log\LogLevel;
26
33 public const CAUGHT_BY_HANDLER = 'mwe_handler';
35 public const CAUGHT_BY_ENTRYPOINT = 'entrypoint';
37 public const CAUGHT_BY_OTHER = 'other';
38
40 protected static $reservedMemory;
41
52 protected static $fatalErrorTypes = [
53 E_ERROR,
54 E_PARSE,
55 E_CORE_ERROR,
56 E_COMPILE_ERROR,
57 E_USER_ERROR,
58
59 // E.g. "Catchable fatal error: Argument X must be Y, null given"
60 E_RECOVERABLE_ERROR,
61 ];
62
66 public static function installHandler() {
67 // This catches:
68 // * Exception objects that were explicitly thrown but not
69 // caught anywhere in the application. This is rare given those
70 // would normally be caught at a high-level like MediaWiki::run (index.php),
71 // api.php, or ResourceLoader::respond (load.php). These high-level
72 // catch clauses would then call MWExceptionHandler::logException
73 // or MWExceptionHandler::handleException.
74 // If they are not caught, then they are handled here.
75 // * Error objects for issues that would historically
76 // cause fatal errors but may now be caught as Throwable (not Exception).
77 // Same as previous case, but more common to bubble to here instead of
78 // caught locally because they tend to not be safe to recover from.
79 // (e.g. argument TypeError, division by zero, etc.)
80 set_exception_handler( 'MWExceptionHandler::handleUncaughtException' );
81
82 // This catches recoverable errors (e.g. PHP Notice, PHP Warning, PHP Error) that do not
83 // interrupt execution in any way. We log these in the background and then continue execution.
84 set_error_handler( 'MWExceptionHandler::handleError' );
85
86 // This catches fatal errors for which no Throwable is thrown,
87 // including Out-Of-Memory and Timeout fatals.
88 // Reserve 16k of memory so we can report OOM fatals.
89 self::$reservedMemory = str_repeat( ' ', 16384 );
90 register_shutdown_function( 'MWExceptionHandler::handleFatalError' );
91 }
92
97 protected static function report( Throwable $e ) {
98 try {
99 // Try and show the exception prettily, with the normal skin infrastructure
100 if ( $e instanceof MWException ) {
101 // Delegate to MWException until all subclasses are handled by
102 // MWExceptionRenderer and MWException::report() has been
103 // removed.
104 $e->report();
105 } else {
107 }
108 } catch ( Throwable $e2 ) {
109 // Exception occurred from within exception handler
110 // Show a simpler message for the original exception,
111 // don't try to invoke report()
113 }
114 }
115
125 public static function rollbackMasterChangesAndLog(
126 Throwable $e,
127 $catcher = self::CAUGHT_BY_OTHER
128 ) {
129 $services = MediaWikiServices::getInstance();
130 if ( !$services->isServiceDisabled( 'DBLoadBalancerFactory' ) ) {
131 // Rollback DBs to avoid transaction notices. This might fail
132 // to rollback some databases due to connection issues or exceptions.
133 // However, any sane DB driver will rollback implicitly anyway.
134 try {
135 $services->getDBLoadBalancerFactory()->rollbackMasterChanges( __METHOD__ );
136 } catch ( DBError $e2 ) {
137 // If the DB is unreacheable, rollback() will throw an error
138 // and the error report() method might need messages from the DB,
139 // which would result in an exception loop. PHP may escalate such
140 // errors to "Exception thrown without a stack frame" fatals, but
141 // it's better to be explicit here.
142 self::logException( $e2, $catcher );
143 }
144 }
145
146 self::logException( $e, $catcher );
147 }
148
155 public static function handleUncaughtException( Throwable $e ) {
156 self::handleException( $e, self::CAUGHT_BY_HANDLER );
157
158 // Make sure we don't claim success on exit for CLI scripts (T177414)
159 if ( wfIsCLI() ) {
160 register_shutdown_function(
161 function () {
162 exit( 255 );
163 }
164 );
165 }
166 }
167
183 public static function handleException( Throwable $e, $catcher = self::CAUGHT_BY_OTHER ) {
184 self::rollbackMasterChangesAndLog( $e, $catcher );
185 self::report( $e );
186 }
187
202 public static function handleError(
203 $level,
204 $message,
205 $file = null,
206 $line = null
207 ) {
208 global $wgPropagateErrors;
209
210 // Map PHP error constant to a PSR-3 severity level.
211 // Avoid use of "DEBUG" or "INFO" levels, unless the
212 // error should evade error monitoring and alerts.
213 //
214 // To decide the log level, ask yourself: "Has the
215 // program's behaviour diverged from what the written
216 // code expected?"
217 //
218 // For example, use of a deprecated method or violating a strict standard
219 // has no impact on functional behaviour (Warning). On the other hand,
220 // accessing an undefined variable makes behaviour diverge from what the
221 // author intended/expected. PHP recovers from an undefined variables by
222 // yielding null and continuing execution, but it remains a change in
223 // behaviour given the null was not part of the code and is likely not
224 // accounted for.
225 switch ( $level ) {
226 case E_WARNING:
227 case E_CORE_WARNING:
228 case E_COMPILE_WARNING:
229 $prefix = 'PHP Warning: ';
230 $severity = LogLevel::ERROR;
231 break;
232 case E_NOTICE:
233 $prefix = 'PHP Notice: ';
234 $severity = LogLevel::ERROR;
235 break;
236 case E_USER_NOTICE:
237 // Used by wfWarn(), MWDebug::warning()
238 $prefix = 'PHP Notice: ';
239 $severity = LogLevel::WARNING;
240 break;
241 case E_USER_WARNING:
242 // Used by wfWarn(), MWDebug::warning()
243 $prefix = 'PHP Warning: ';
244 $severity = LogLevel::WARNING;
245 break;
246 case E_STRICT:
247 $prefix = 'PHP Strict Standards: ';
248 $severity = LogLevel::WARNING;
249 break;
250 case E_DEPRECATED:
251 case E_USER_DEPRECATED:
252 $prefix = 'PHP Deprecated: ';
253 $severity = LogLevel::WARNING;
254 break;
255 default:
256 $prefix = 'PHP Unknown error: ';
257 $severity = LogLevel::ERROR;
258 break;
259 }
260
261 $e = new ErrorException( $prefix . $message, 0, $level, $file, $line );
262 self::logError( $e, 'error', $severity, self::CAUGHT_BY_HANDLER );
263
264 // If $wgPropagateErrors is true return false so PHP shows/logs the error normally.
265 // Ignore $wgPropagateErrors if track_errors is set
266 // (which means someone is counting on regular PHP error handling behavior).
267 return !( $wgPropagateErrors || ini_get( 'track_errors' ) );
268 }
269
284 public static function handleFatalError() {
285 // Free reserved memory so that we have space to process OOM
286 // errors
287 self::$reservedMemory = null;
288
289 $lastError = error_get_last();
290 if ( $lastError !== null ) {
291 $level = $lastError['type'];
292 $message = $lastError['message'];
293 $file = $lastError['file'];
294 $line = $lastError['line'];
295 } else {
296 $level = 0;
297 $message = '';
298 }
299
300 if ( !in_array( $level, self::$fatalErrorTypes ) ) {
301 // Only interested in fatal errors, others should have been
302 // handled by MWExceptionHandler::handleError
303 return false;
304 }
305
306 $url = WebRequest::getGlobalRequestURL();
307 $msgParts = [
308 '[{exception_id}] {exception_url} PHP Fatal Error',
309 ( $line || $file ) ? ' from' : '',
310 $line ? " line $line" : '',
311 ( $line && $file ) ? ' of' : '',
312 $file ? " $file" : '',
313 ": $message",
314 ];
315 $msg = implode( '', $msgParts );
316
317 // Look at message to see if this is a class not found failure (Class 'foo' not found)
318 if ( preg_match( "/Class '\w+' not found/", $message ) ) {
319 // phpcs:disable Generic.Files.LineLength
320 $msg = <<<TXT
321{$msg}
322
323MediaWiki 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.
324
325Please see <a href="https://www.mediawiki.org/wiki/Download_from_Git#Fetch_external_libraries">mediawiki.org</a> for help on installing the required components.
326TXT;
327 // phpcs:enable
328 }
329
330 $e = new ErrorException( "PHP Fatal Error: {$message}", 0, $level, $file, $line );
331 $logger = LoggerFactory::getInstance( 'exception' );
332 $logger->error( $msg, [
333 'exception' => $e,
334 'exception_id' => WebRequest::getRequestId(),
335 'exception_url' => $url,
336 'caught_by' => self::CAUGHT_BY_HANDLER
337 ] );
338
339 return false;
340 }
341
352 public static function getRedactedTraceAsString( Throwable $e ) {
353 return self::prettyPrintTrace( self::getRedactedTrace( $e ) );
354 }
355
364 public static function prettyPrintTrace( array $trace, $pad = '' ) {
365 $text = '';
366
367 $level = 0;
368 foreach ( $trace as $level => $frame ) {
369 if ( isset( $frame['file'] ) && isset( $frame['line'] ) ) {
370 $text .= "{$pad}#{$level} {$frame['file']}({$frame['line']}): ";
371 } else {
372 // 'file' and 'line' are unset for calls from C code
373 // (T57634) This matches behaviour of
374 // Throwable::getTraceAsString to instead display "[internal
375 // function]".
376 $text .= "{$pad}#{$level} [internal function]: ";
377 }
378
379 if ( isset( $frame['class'] ) && isset( $frame['type'] ) && isset( $frame['function'] ) ) {
380 $text .= $frame['class'] . $frame['type'] . $frame['function'];
381 } elseif ( isset( $frame['function'] ) ) {
382 $text .= $frame['function'];
383 } else {
384 $text .= 'NO_FUNCTION_GIVEN';
385 }
386
387 if ( isset( $frame['args'] ) ) {
388 $text .= '(' . implode( ', ', $frame['args'] ) . ")\n";
389 } else {
390 $text .= "()\n";
391 }
392 }
393
394 $level += 1;
395 $text .= "{$pad}#{$level} {main}";
396
397 return $text;
398 }
399
411 public static function getRedactedTrace( Throwable $e ) {
412 return static::redactTrace( $e->getTrace() );
413 }
414
425 public static function redactTrace( array $trace ) {
426 return array_map( function ( $frame ) {
427 if ( isset( $frame['args'] ) ) {
428 $frame['args'] = array_map( function ( $arg ) {
429 return is_object( $arg ) ? get_class( $arg ) : gettype( $arg );
430 }, $frame['args'] );
431 }
432 return $frame;
433 }, $trace );
434 }
435
443 public static function getURL() {
444 global $wgRequest;
445 if ( !isset( $wgRequest ) || $wgRequest instanceof FauxRequest ) {
446 return false;
447 }
448 return $wgRequest->getRequestURL();
449 }
450
462 public static function getLogMessage( Throwable $e ) {
463 $id = WebRequest::getRequestId();
464 $type = get_class( $e );
465 $file = $e->getFile();
466 $line = $e->getLine();
467 $message = $e->getMessage();
468 $url = self::getURL() ?: '[no req]';
469
470 if ( $e instanceof DBQueryError ) {
471 $message = "A database query error has occurred. Did you forget to run"
472 . " your application's database schema updater after upgrading?\n\n"
473 . $message;
474 }
475
476 return "[$id] $url $type from line $line of $file: $message";
477 }
478
488 public static function getLogNormalMessage( Throwable $e ) {
489 $type = get_class( $e );
490 $file = $e->getFile();
491 $line = $e->getLine();
492 $message = $e->getMessage();
493
494 return "[{exception_id}] {exception_url} $type from line $line of $file: $message";
495 }
496
501 public static function getPublicLogMessage( Throwable $e ) {
502 $reqId = WebRequest::getRequestId();
503 $type = get_class( $e );
504 return '[' . $reqId . '] '
505 . gmdate( 'Y-m-d H:i:s' ) . ': '
506 . 'Fatal exception of type "' . $type . '"';
507 }
508
521 public static function getLogContext( Throwable $e, $catcher = self::CAUGHT_BY_OTHER ) {
522 return [
523 'exception' => $e,
524 'exception_id' => WebRequest::getRequestId(),
525 'exception_url' => self::getURL() ?: '[no req]',
526 'caught_by' => $catcher
527 ];
528 }
529
542 public static function getStructuredExceptionData(
543 Throwable $e,
544 $catcher = self::CAUGHT_BY_OTHER
545 ) {
547
548 $data = [
549 'id' => WebRequest::getRequestId(),
550 'type' => get_class( $e ),
551 'file' => $e->getFile(),
552 'line' => $e->getLine(),
553 'message' => $e->getMessage(),
554 'code' => $e->getCode(),
555 'url' => self::getURL() ?: null,
556 'caught_by' => $catcher
557 ];
558
559 if ( $e instanceof ErrorException &&
560 ( error_reporting() & $e->getSeverity() ) === 0
561 ) {
562 // Flag surpressed errors
563 $data['suppressed'] = true;
564 }
565
567 $data['backtrace'] = self::getRedactedTrace( $e );
568 }
569
570 $previous = $e->getPrevious();
571 if ( $previous !== null ) {
572 $data['previous'] = self::getStructuredExceptionData( $previous, $catcher );
573 }
574
575 return $data;
576 }
577
632 public static function jsonSerializeException(
633 Throwable $e,
634 $pretty = false,
635 $escaping = 0,
636 $catcher = self::CAUGHT_BY_OTHER
637 ) {
638 return FormatJson::encode(
639 self::getStructuredExceptionData( $e, $catcher ),
640 $pretty,
641 $escaping
642 );
643 }
644
656 public static function logException(
657 Throwable $e,
658 $catcher = self::CAUGHT_BY_OTHER,
659 $extraData = []
660 ) {
661 if ( !( $e instanceof MWException ) || $e->isLoggable() ) {
662 $logger = LoggerFactory::getInstance( 'exception' );
663 $context = self::getLogContext( $e, $catcher );
664 if ( $extraData ) {
665 $context['extraData'] = $extraData;
666 }
667 $logger->error(
668 self::getLogNormalMessage( $e ),
669 $context
670 );
671
672 $json = self::jsonSerializeException( $e, false, FormatJson::ALL_OK, $catcher );
673 if ( $json !== false ) {
674 $logger = LoggerFactory::getInstance( 'exception-json' );
675 $logger->error( $json, [ 'private' => true ] );
676 }
677
678 Hooks::runner()->onLogException( $e, false );
679 }
680 }
681
690 private static function logError(
691 ErrorException $e,
692 $channel,
693 $level,
694 $catcher
695 ) {
696 // The set_error_handler callback is independent from error_reporting.
697 // Filter out unwanted errors manually (e.g. when
698 // Wikimedia\suppressWarnings is active).
699 $suppressed = ( error_reporting() & $e->getSeverity() ) === 0;
700 if ( !$suppressed ) {
701 $logger = LoggerFactory::getInstance( $channel );
702 $logger->log(
703 $level,
704 self::getLogNormalMessage( $e ),
705 self::getLogContext( $e, $catcher )
706 );
707 }
708
709 // Include all errors in the json log (surpressed errors will be flagged)
710 $json = self::jsonSerializeException( $e, false, FormatJson::ALL_OK, $catcher );
711 if ( $json !== false ) {
712 $logger = LoggerFactory::getInstance( "{$channel}-json" );
713 // Unlike the 'error' channel, the 'error-json' channel is unfiltered,
714 // and emits messages even if wikimedia/at-ease was used to suppress the
715 // error. To avoid clobbering Logstash dashboards with these, make sure
716 // those have their level casted to DEBUG so that they are excluded by
717 // level-based filteres automatically instead of requiring a dedicated filter
718 // for this channel. To be improved: T193472.
719 $unfilteredLevel = $suppressed ? LogLevel::DEBUG : $level;
720 $logger->log( $unfilteredLevel, $json, [ 'private' => true ] );
721 }
722
723 Hooks::runner()->onLogException( $e, $suppressed );
724 }
725}
$wgLogExceptionBacktrace
If true, send the exception backtrace to the error log.
$wgPropagateErrors
If true, the MediaWiki error handler passes errors/warnings to the default error handler after loggin...
wfIsCLI()
Check if we are running from the commandline.
if(! $wgDBerrorLogTZ) $wgRequest
Definition Setup.php:643
WebRequest clone which takes values from a provided array.
Handler class for MWExceptions.
static getLogContext(Throwable $e, $catcher=self::CAUGHT_BY_OTHER)
Get a PSR-3 log event context from a Throwable.
static handleError( $level, $message, $file=null, $line=null)
Handler for set_error_handler() callback notifications.
static getStructuredExceptionData(Throwable $e, $catcher=self::CAUGHT_BY_OTHER)
Get a structured representation of a Throwable.
static rollbackMasterChangesAndLog(Throwable $e, $catcher=self::CAUGHT_BY_OTHER)
Roll back any open database transactions and log the stack trace of the throwable.
static getRedactedTraceAsString(Throwable $e)
Generate a string representation of a throwable's stack trace.
static report(Throwable $e)
Report a throwable to the user.
static logException(Throwable $e, $catcher=self::CAUGHT_BY_OTHER, $extraData=[])
Log a throwable to the exception log (if enabled).
static $fatalErrorTypes
Error types that, if unhandled, are fatal to the request.
static getPublicLogMessage(Throwable $e)
static getRedactedTrace(Throwable $e)
Return a copy of a throwable's backtrace as an array.
static handleUncaughtException(Throwable $e)
Callback to use with PHP's set_exception_handler.
static prettyPrintTrace(array $trace, $pad='')
Generate a string representation of a stacktrace.
static jsonSerializeException(Throwable $e, $pretty=false, $escaping=0, $catcher=self::CAUGHT_BY_OTHER)
Serialize a Throwable object to JSON.
static logError(ErrorException $e, $channel, $level, $catcher)
Log an exception that wasn't thrown but made to wrap an error.
static getLogMessage(Throwable $e)
Get a message formatting the throwable message and its origin.
static redactTrace(array $trace)
Redact a stacktrace generated by Throwable::getTrace(), debug_backtrace() or similar means.
static installHandler()
Install handlers with PHP.
static handleFatalError()
Callback used as a registered shutdown function.
static getLogNormalMessage(Throwable $e)
Get a normalised message for formatting with PSR-3 log event context.
static getURL()
If the exception occurred in the course of responding to a request, returns the requested URL.
static handleException(Throwable $e, $catcher=self::CAUGHT_BY_OTHER)
Exception handler which simulates the appropriate catch() handling:
static output(Throwable $e, $mode, Throwable $eNew=null)
MediaWiki exception.
PSR-3 logger instance factory.
MediaWikiServices is the service locator for the application scope of MediaWiki.
Database error base class @newable Stable to extend.
Definition DBError.php:32
@newable Stable to extend
$line
Definition mcc.php:119
A helper class for throttling authentication attempts.
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition router.php:42