Merge "FauxRequest: don’t override getValues()"
[lhc/web/wiklou.git] / includes / exception / MWExceptionHandler.php
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.
7 *
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.
12 *
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
17 *
18 * @file
19 */
20
21 use MediaWiki\Logger\LoggerFactory;
22 use MediaWiki\MediaWikiServices;
23 use Psr\Log\LogLevel;
24 use Wikimedia\Rdbms\DBError;
25
26 /**
27 * Handler class for MWExceptions
28 * @ingroup Exception
29 */
30 class MWExceptionHandler {
31 const CAUGHT_BY_HANDLER = 'mwe_handler'; // error reported by this exception handler
32 const CAUGHT_BY_OTHER = 'other'; // error reported by direct logException() call
33
34 /**
35 * @var string $reservedMemory
36 */
37 protected static $reservedMemory;
38
39 /**
40 * Error types that, if unhandled, are fatal to the request.
41 *
42 * On PHP 7, these error types may be thrown as Error objects, which
43 * implement Throwable (but not Exception).
44 *
45 * On HHVM, these invoke the set_error_handler callback, similar to how
46 * (non-fatal) warnings and notices are reported, except that after this
47 * handler runs for fatal error tpyes, script execution stops!
48 *
49 * The user will be shown an HTTP 500 Internal Server Error.
50 * As such, these should be sent to MediaWiki's "fatal" or "exception"
51 * channel. Normally, the error handler logs them to the "error" channel.
52 *
53 * @var array $fatalErrorTypes
54 */
55 protected static $fatalErrorTypes = [
56 E_ERROR,
57 E_PARSE,
58 E_CORE_ERROR,
59 E_COMPILE_ERROR,
60 E_USER_ERROR,
61
62 // E.g. "Catchable fatal error: Argument X must be Y, null given"
63 E_RECOVERABLE_ERROR,
64
65 // HHVM's FATAL_ERROR constant
66 16777217,
67 ];
68 /**
69 * @var bool $handledFatalCallback
70 */
71 protected static $handledFatalCallback = false;
72
73 /**
74 * Install handlers with PHP.
75 */
76 public static function installHandler() {
77 // This catches:
78 // * Exception objects that were explicitly thrown but not
79 // caught anywhere in the application. This is rare given those
80 // would normally be caught at a high-level like MediaWiki::run (index.php),
81 // api.php, or ResourceLoader::respond (load.php). These high-level
82 // catch clauses would then call MWExceptionHandler::logException
83 // or MWExceptionHandler::handleException.
84 // If they are not caught, then they are handled here.
85 // * Error objects (on PHP 7+), for issues that would historically
86 // cause fatal errors but may now be caught as Throwable (not Exception).
87 // Same as previous case, but more common to bubble to here instead of
88 // caught locally because they tend to not be safe to recover from.
89 // (e.g. argument TypeErorr, devision by zero, etc.)
90 set_exception_handler( 'MWExceptionHandler::handleUncaughtException' );
91
92 // This catches:
93 // * Non-fatal errors (e.g. PHP Notice, PHP Warning, PHP Error) that do not
94 // interrupt execution in any way. We log these in the background and then
95 // continue execution.
96 // * Fatal errors (on HHVM in PHP5 mode) where PHP 7 would throw Throwable.
97 set_error_handler( 'MWExceptionHandler::handleError' );
98
99 // This catches:
100 // * Fatal error for which no Throwable is thrown (PHP 7), and no Error emitted (HHVM).
101 // This includes Out-Of-Memory and Timeout fatals.
102 //
103 // Reserve 16k of memory so we can report OOM fatals
104 self::$reservedMemory = str_repeat( ' ', 16384 );
105 register_shutdown_function( 'MWExceptionHandler::handleFatalError' );
106 }
107
108 /**
109 * Report an exception to the user
110 * @param Exception|Throwable $e
111 */
112 protected static function report( $e ) {
113 try {
114 // Try and show the exception prettily, with the normal skin infrastructure
115 if ( $e instanceof MWException ) {
116 // Delegate to MWException until all subclasses are handled by
117 // MWExceptionRenderer and MWException::report() has been
118 // removed.
119 $e->report();
120 } else {
121 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_PRETTY );
122 }
123 } catch ( Exception $e2 ) {
124 // Exception occurred from within exception handler
125 // Show a simpler message for the original exception,
126 // don't try to invoke report()
127 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_RAW, $e2 );
128 }
129 }
130
131 /**
132 * Roll back any open database transactions and log the stack trace of the exception
133 *
134 * This method is used to attempt to recover from exceptions
135 *
136 * @since 1.23
137 * @param Exception|Throwable $e
138 */
139 public static function rollbackMasterChangesAndLog( $e ) {
140 $services = MediaWikiServices::getInstance();
141 if ( !$services->isServiceDisabled( 'DBLoadBalancerFactory' ) ) {
142 // Rollback DBs to avoid transaction notices. This might fail
143 // to rollback some databases due to connection issues or exceptions.
144 // However, any sane DB driver will rollback implicitly anyway.
145 try {
146 $services->getDBLoadBalancerFactory()->rollbackMasterChanges( __METHOD__ );
147 } catch ( DBError $e2 ) {
148 // If the DB is unreacheable, rollback() will throw an error
149 // and the error report() method might need messages from the DB,
150 // which would result in an exception loop. PHP may escalate such
151 // errors to "Exception thrown without a stack frame" fatals, but
152 // it's better to be explicit here.
153 self::logException( $e2, self::CAUGHT_BY_HANDLER );
154 }
155 }
156
157 self::logException( $e, self::CAUGHT_BY_HANDLER );
158 }
159
160 /**
161 * Callback to use with PHP's set_exception_handler.
162 *
163 * @since 1.31
164 * @param Exception|Throwable $e
165 */
166 public static function handleUncaughtException( $e ) {
167 self::handleException( $e );
168
169 // Make sure we don't claim success on exit for CLI scripts (T177414)
170 if ( wfIsCLI() ) {
171 register_shutdown_function(
172 function () {
173 exit( 255 );
174 }
175 );
176 }
177 }
178
179 /**
180 * Exception handler which simulates the appropriate catch() handling:
181 *
182 * try {
183 * ...
184 * } catch ( Exception $e ) {
185 * $e->report();
186 * } catch ( Exception $e ) {
187 * echo $e->__toString();
188 * }
189 *
190 * @since 1.25
191 * @param Exception|Throwable $e
192 */
193 public static function handleException( $e ) {
194 self::rollbackMasterChangesAndLog( $e );
195 self::report( $e );
196 }
197
198 /**
199 * Handler for set_error_handler() callback notifications.
200 *
201 * Receive a callback from the interpreter for a raised error, create an
202 * ErrorException, and log the exception to the 'error' logging
203 * channel(s). If the raised error is a fatal error type (only under HHVM)
204 * delegate to handleFatalError() instead.
205 *
206 * @since 1.25
207 *
208 * @param int $level Error level raised
209 * @param string $message
210 * @param string|null $file
211 * @param int|null $line
212 * @return bool
213 *
214 * @see logError()
215 */
216 public static function handleError(
217 $level, $message, $file = null, $line = null
218 ) {
219 global $wgPropagateErrors;
220
221 if ( in_array( $level, self::$fatalErrorTypes ) ) {
222 return self::handleFatalError( ...func_get_args() );
223 }
224
225 // Map PHP error constant to a PSR-3 severity level.
226 // Avoid use of "DEBUG" or "INFO" levels, unless the
227 // error should evade error monitoring and alerts.
228 //
229 // To decide the log level, ask yourself: "Has the
230 // program's behaviour diverged from what the written
231 // code expected?"
232 //
233 // For example, use of a deprecated method or violating a strict standard
234 // has no impact on functional behaviour (Warning). On the other hand,
235 // accessing an undefined variable makes behaviour diverge from what the
236 // author intended/expected. PHP recovers from an undefined variables by
237 // yielding null and continuing execution, but it remains a change in
238 // behaviour given the null was not part of the code and is likely not
239 // accounted for.
240 switch ( $level ) {
241 case E_WARNING:
242 case E_CORE_WARNING:
243 case E_COMPILE_WARNING:
244 $levelName = 'Warning';
245 $severity = LogLevel::ERROR;
246 break;
247 case E_NOTICE:
248 $levelName = 'Notice';
249 $severity = LogLevel::ERROR;
250 break;
251 case E_USER_NOTICE:
252 // Used by wfWarn(), MWDebug::warning()
253 $levelName = 'Notice';
254 $severity = LogLevel::WARNING;
255 break;
256 case E_USER_WARNING:
257 // Used by wfWarn(), MWDebug::warning()
258 $levelName = 'Warning';
259 $severity = LogLevel::WARNING;
260 break;
261 case E_STRICT:
262 $levelName = 'Strict Standards';
263 $severity = LogLevel::WARNING;
264 break;
265 case E_DEPRECATED:
266 case E_USER_DEPRECATED:
267 $levelName = 'Deprecated';
268 $severity = LogLevel::WARNING;
269 break;
270 default:
271 $levelName = 'Unknown error';
272 $severity = LogLevel::ERROR;
273 break;
274 }
275
276 $e = new ErrorException( "PHP $levelName: $message", 0, $level, $file, $line );
277 self::logError( $e, 'error', $severity );
278
279 // If $wgPropagateErrors is true return false so PHP shows/logs the error normally.
280 // Ignore $wgPropagateErrors if track_errors is set
281 // (which means someone is counting on regular PHP error handling behavior).
282 return !( $wgPropagateErrors || ini_get( 'track_errors' ) );
283 }
284
285 /**
286 * Dual purpose callback used as both a set_error_handler() callback and
287 * a registered shutdown function. Receive a callback from the interpreter
288 * for a raised error or system shutdown, check for a fatal error, and log
289 * to the 'fatal' logging channel.
290 *
291 * Special handling is included for missing class errors as they may
292 * indicate that the user needs to install 3rd-party libraries via
293 * Composer or other means.
294 *
295 * @since 1.25
296 *
297 * @param int|null $level Error level raised
298 * @param string|null $message Error message
299 * @param string|null $file File that error was raised in
300 * @param int|null $line Line number error was raised at
301 * @param array|null $context Active symbol table point of error
302 * @param array|null $trace Backtrace at point of error (undocumented HHVM
303 * feature)
304 * @return bool Always returns false
305 */
306 public static function handleFatalError(
307 $level = null, $message = null, $file = null, $line = null,
308 $context = null, $trace = null
309 ) {
310 // Free reserved memory so that we have space to process OOM
311 // errors
312 self::$reservedMemory = null;
313
314 if ( $level === null ) {
315 // Called as a shutdown handler, get data from error_get_last()
316 if ( static::$handledFatalCallback ) {
317 // Already called once (probably as an error handler callback
318 // under HHVM) so don't log again.
319 return false;
320 }
321
322 $lastError = error_get_last();
323 if ( $lastError !== null ) {
324 $level = $lastError['type'];
325 $message = $lastError['message'];
326 $file = $lastError['file'];
327 $line = $lastError['line'];
328 } else {
329 $level = 0;
330 $message = '';
331 }
332 }
333
334 if ( !in_array( $level, self::$fatalErrorTypes ) ) {
335 // Only interested in fatal errors, others should have been
336 // handled by MWExceptionHandler::handleError
337 return false;
338 }
339
340 $url = WebRequest::getGlobalRequestURL();
341 $msgParts = [
342 '[{exception_id}] {exception_url} PHP Fatal Error',
343 ( $line || $file ) ? ' from' : '',
344 $line ? " line $line" : '',
345 ( $line && $file ) ? ' of' : '',
346 $file ? " $file" : '',
347 ": $message",
348 ];
349 $msg = implode( '', $msgParts );
350
351 // Look at message to see if this is a class not found failure
352 // HHVM: Class undefined: foo
353 // PHP7: Class 'foo' not found
354 if ( preg_match( "/Class (undefined: \w+|'\w+' not found)/", $message ) ) {
355 // phpcs:disable Generic.Files.LineLength
356 $msg = <<<TXT
357 {$msg}
358
359 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.
360
361 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.
362 TXT;
363 // phpcs:enable
364 }
365
366 // We can't just create an exception and log it as it is likely that
367 // the interpreter has unwound the stack already. If that is true the
368 // stacktrace we would get would be functionally empty. If however we
369 // have been called as an error handler callback *and* HHVM is in use
370 // we will have been provided with a useful stacktrace that we can
371 // log.
372 $trace = $trace ?: debug_backtrace();
373 $logger = LoggerFactory::getInstance( 'fatal' );
374 $logger->error( $msg, [
375 'fatal_exception' => [
376 'class' => ErrorException::class,
377 'message' => "PHP Fatal Error: {$message}",
378 'code' => $level,
379 'file' => $file,
380 'line' => $line,
381 'trace' => self::prettyPrintTrace( self::redactTrace( $trace ) ),
382 ],
383 'exception_id' => WebRequest::getRequestId(),
384 'exception_url' => $url,
385 'caught_by' => self::CAUGHT_BY_HANDLER
386 ] );
387
388 // Remember call so we don't double process via HHVM's fatal
389 // notifications and the shutdown hook behavior
390 static::$handledFatalCallback = true;
391 return false;
392 }
393
394 /**
395 * Generate a string representation of an exception's stack trace
396 *
397 * Like Exception::getTraceAsString, but replaces argument values with
398 * argument type or class name.
399 *
400 * @param Exception|Throwable $e
401 * @return string
402 * @see prettyPrintTrace()
403 */
404 public static function getRedactedTraceAsString( $e ) {
405 return self::prettyPrintTrace( self::getRedactedTrace( $e ) );
406 }
407
408 /**
409 * Generate a string representation of a stacktrace.
410 *
411 * @param array $trace
412 * @param string $pad Constant padding to add to each line of trace
413 * @return string
414 * @since 1.26
415 */
416 public static function prettyPrintTrace( array $trace, $pad = '' ) {
417 $text = '';
418
419 $level = 0;
420 foreach ( $trace as $level => $frame ) {
421 if ( isset( $frame['file'] ) && isset( $frame['line'] ) ) {
422 $text .= "{$pad}#{$level} {$frame['file']}({$frame['line']}): ";
423 } else {
424 // 'file' and 'line' are unset for calls via call_user_func
425 // (T57634) This matches behaviour of
426 // Exception::getTraceAsString to instead display "[internal
427 // function]".
428 $text .= "{$pad}#{$level} [internal function]: ";
429 }
430
431 if ( isset( $frame['class'] ) && isset( $frame['type'] ) && isset( $frame['function'] ) ) {
432 $text .= $frame['class'] . $frame['type'] . $frame['function'];
433 } elseif ( isset( $frame['function'] ) ) {
434 $text .= $frame['function'];
435 } else {
436 $text .= 'NO_FUNCTION_GIVEN';
437 }
438
439 if ( isset( $frame['args'] ) ) {
440 $text .= '(' . implode( ', ', $frame['args'] ) . ")\n";
441 } else {
442 $text .= "()\n";
443 }
444 }
445
446 $level = $level + 1;
447 $text .= "{$pad}#{$level} {main}";
448
449 return $text;
450 }
451
452 /**
453 * Return a copy of an exception's backtrace as an array.
454 *
455 * Like Exception::getTrace, but replaces each element in each frame's
456 * argument array with the name of its class (if the element is an object)
457 * or its type (if the element is a PHP primitive).
458 *
459 * @since 1.22
460 * @param Exception|Throwable $e
461 * @return array
462 */
463 public static function getRedactedTrace( $e ) {
464 return static::redactTrace( $e->getTrace() );
465 }
466
467 /**
468 * Redact a stacktrace generated by Exception::getTrace(),
469 * debug_backtrace() or similar means. Replaces each element in each
470 * frame's argument array with the name of its class (if the element is an
471 * object) or its type (if the element is a PHP primitive).
472 *
473 * @since 1.26
474 * @param array $trace Stacktrace
475 * @return array Stacktrace with arugment values converted to data types
476 */
477 public static function redactTrace( array $trace ) {
478 return array_map( function ( $frame ) {
479 if ( isset( $frame['args'] ) ) {
480 $frame['args'] = array_map( function ( $arg ) {
481 return is_object( $arg ) ? get_class( $arg ) : gettype( $arg );
482 }, $frame['args'] );
483 }
484 return $frame;
485 }, $trace );
486 }
487
488 /**
489 * If the exception occurred in the course of responding to a request,
490 * returns the requested URL. Otherwise, returns false.
491 *
492 * @since 1.23
493 * @return string|false
494 */
495 public static function getURL() {
496 global $wgRequest;
497 if ( !isset( $wgRequest ) || $wgRequest instanceof FauxRequest ) {
498 return false;
499 }
500 return $wgRequest->getRequestURL();
501 }
502
503 /**
504 * Get a message formatting the exception message and its origin.
505 *
506 * @since 1.22
507 * @param Exception|Throwable $e
508 * @return string
509 */
510 public static function getLogMessage( $e ) {
511 $id = WebRequest::getRequestId();
512 $type = get_class( $e );
513 $file = $e->getFile();
514 $line = $e->getLine();
515 $message = $e->getMessage();
516 $url = self::getURL() ?: '[no req]';
517
518 return "[$id] $url $type from line $line of $file: $message";
519 }
520
521 /**
522 * Get a normalised message for formatting with PSR-3 log event context.
523 *
524 * Must be used together with `getLogContext()` to be useful.
525 *
526 * @since 1.30
527 * @param Exception|Throwable $e
528 * @return string
529 */
530 public static function getLogNormalMessage( $e ) {
531 $type = get_class( $e );
532 $file = $e->getFile();
533 $line = $e->getLine();
534 $message = $e->getMessage();
535
536 return "[{exception_id}] {exception_url} $type from line $line of $file: $message";
537 }
538
539 /**
540 * @param Exception|Throwable $e
541 * @return string
542 */
543 public static function getPublicLogMessage( $e ) {
544 $reqId = WebRequest::getRequestId();
545 $type = get_class( $e );
546 return '[' . $reqId . '] '
547 . gmdate( 'Y-m-d H:i:s' ) . ': '
548 . 'Fatal exception of type "' . $type . '"';
549 }
550
551 /**
552 * Get a PSR-3 log event context from an Exception.
553 *
554 * Creates a structured array containing information about the provided
555 * exception that can be used to augment a log message sent to a PSR-3
556 * logger.
557 *
558 * @param Exception|Throwable $e
559 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
560 * @return array
561 */
562 public static function getLogContext( $e, $catcher = self::CAUGHT_BY_OTHER ) {
563 return [
564 'exception' => $e,
565 'exception_id' => WebRequest::getRequestId(),
566 'exception_url' => self::getURL() ?: '[no req]',
567 'caught_by' => $catcher
568 ];
569 }
570
571 /**
572 * Get a structured representation of an Exception.
573 *
574 * Returns an array of structured data (class, message, code, file,
575 * backtrace) derived from the given exception. The backtrace information
576 * will be redacted as per getRedactedTraceAsArray().
577 *
578 * @param Exception|Throwable $e
579 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
580 * @return array
581 * @since 1.26
582 */
583 public static function getStructuredExceptionData( $e, $catcher = self::CAUGHT_BY_OTHER ) {
584 global $wgLogExceptionBacktrace;
585
586 $data = [
587 'id' => WebRequest::getRequestId(),
588 'type' => get_class( $e ),
589 'file' => $e->getFile(),
590 'line' => $e->getLine(),
591 'message' => $e->getMessage(),
592 'code' => $e->getCode(),
593 'url' => self::getURL() ?: null,
594 'caught_by' => $catcher
595 ];
596
597 if ( $e instanceof ErrorException &&
598 ( error_reporting() & $e->getSeverity() ) === 0
599 ) {
600 // Flag surpressed errors
601 $data['suppressed'] = true;
602 }
603
604 if ( $wgLogExceptionBacktrace ) {
605 $data['backtrace'] = self::getRedactedTrace( $e );
606 }
607
608 $previous = $e->getPrevious();
609 if ( $previous !== null ) {
610 $data['previous'] = self::getStructuredExceptionData( $previous, $catcher );
611 }
612
613 return $data;
614 }
615
616 /**
617 * Serialize an Exception object to JSON.
618 *
619 * The JSON object will have keys 'id', 'file', 'line', 'message', and
620 * 'url'. These keys map to string values, with the exception of 'line',
621 * which is a number, and 'url', which may be either a string URL or or
622 * null if the exception did not occur in the context of serving a web
623 * request.
624 *
625 * If $wgLogExceptionBacktrace is true, it will also have a 'backtrace'
626 * key, mapped to the array return value of Exception::getTrace, but with
627 * each element in each frame's "args" array (if set) replaced with the
628 * argument's class name (if the argument is an object) or type name (if
629 * the argument is a PHP primitive).
630 *
631 * @par Sample JSON record ($wgLogExceptionBacktrace = false):
632 * @code
633 * {
634 * "id": "c41fb419",
635 * "type": "MWException",
636 * "file": "/var/www/mediawiki/includes/cache/MessageCache.php",
637 * "line": 704,
638 * "message": "Non-string key given",
639 * "url": "/wiki/Main_Page"
640 * }
641 * @endcode
642 *
643 * @par Sample JSON record ($wgLogExceptionBacktrace = true):
644 * @code
645 * {
646 * "id": "dc457938",
647 * "type": "MWException",
648 * "file": "/vagrant/mediawiki/includes/cache/MessageCache.php",
649 * "line": 704,
650 * "message": "Non-string key given",
651 * "url": "/wiki/Main_Page",
652 * "backtrace": [{
653 * "file": "/vagrant/mediawiki/extensions/VisualEditor/VisualEditor.hooks.php",
654 * "line": 80,
655 * "function": "get",
656 * "class": "MessageCache",
657 * "type": "->",
658 * "args": ["array"]
659 * }]
660 * }
661 * @endcode
662 *
663 * @since 1.23
664 * @param Exception|Throwable $e
665 * @param bool $pretty Add non-significant whitespace to improve readability (default: false).
666 * @param int $escaping Bitfield consisting of FormatJson::.*_OK class constants.
667 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
668 * @return string|false JSON string if successful; false upon failure
669 */
670 public static function jsonSerializeException(
671 $e, $pretty = false, $escaping = 0, $catcher = self::CAUGHT_BY_OTHER
672 ) {
673 return FormatJson::encode(
674 self::getStructuredExceptionData( $e, $catcher ),
675 $pretty,
676 $escaping
677 );
678 }
679
680 /**
681 * Log an exception to the exception log (if enabled).
682 *
683 * This method must not assume the exception is an MWException,
684 * it is also used to handle PHP exceptions or exceptions from other libraries.
685 *
686 * @param Exception|Throwable $e
687 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
688 * @param array $extraData (since 1.34) Additional data to log
689 * @since 1.22
690 */
691 public static function logException( $e, $catcher = self::CAUGHT_BY_OTHER, $extraData = [] ) {
692 if ( !( $e instanceof MWException ) || $e->isLoggable() ) {
693 $logger = LoggerFactory::getInstance( 'exception' );
694 $context = self::getLogContext( $e, $catcher );
695 if ( $extraData ) {
696 $context['extraData'] = $extraData;
697 }
698 $logger->error(
699 self::getLogNormalMessage( $e ),
700 $context
701 );
702
703 $json = self::jsonSerializeException( $e, false, FormatJson::ALL_OK, $catcher );
704 if ( $json !== false ) {
705 $logger = LoggerFactory::getInstance( 'exception-json' );
706 $logger->error( $json, [ 'private' => true ] );
707 }
708
709 Hooks::run( 'LogException', [ $e, false ] );
710 }
711 }
712
713 /**
714 * Log an exception that wasn't thrown but made to wrap an error.
715 *
716 * @since 1.25
717 * @param ErrorException $e
718 * @param string $channel
719 * @param string $level
720 */
721 protected static function logError(
722 ErrorException $e, $channel, $level = LogLevel::ERROR
723 ) {
724 $catcher = self::CAUGHT_BY_HANDLER;
725 // The set_error_handler callback is independent from error_reporting.
726 // Filter out unwanted errors manually (e.g. when
727 // Wikimedia\suppressWarnings is active).
728 $suppressed = ( error_reporting() & $e->getSeverity() ) === 0;
729 if ( !$suppressed ) {
730 $logger = LoggerFactory::getInstance( $channel );
731 $logger->log(
732 $level,
733 self::getLogNormalMessage( $e ),
734 self::getLogContext( $e, $catcher )
735 );
736 }
737
738 // Include all errors in the json log (surpressed errors will be flagged)
739 $json = self::jsonSerializeException( $e, false, FormatJson::ALL_OK, $catcher );
740 if ( $json !== false ) {
741 $logger = LoggerFactory::getInstance( "{$channel}-json" );
742 $logger->log( $level, $json, [ 'private' => true ] );
743 }
744
745 Hooks::run( 'LogException', [ $e, $suppressed ] );
746 }
747 }