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 * Install an exception handler for MediaWiki exception types.
29 public static function installHandler() {
30 set_exception_handler( array( 'MWExceptionHandler', 'handle' ) );
34 * Report an exception to the user
37 protected static function report( Exception
$e ) {
38 global $wgShowExceptionDetails;
40 $cmdLine = MWException
::isCommandLine();
42 if ( $e instanceof MWException
) {
44 // Try and show the exception prettily, with the normal skin infrastructure
46 } catch ( Exception
$e2 ) {
47 // Exception occurred from within exception handler
48 // Show a simpler error message for the original exception,
49 // don't try to invoke report()
50 $message = "MediaWiki internal error.\n\n";
52 if ( $wgShowExceptionDetails ) {
53 $message .= 'Original exception: ' . self
::getLogMessage( $e ) .
54 "\nBacktrace:\n" . self
::getRedactedTraceAsString( $e ) .
55 "\n\nException caught inside exception handler: " . self
::getLogMessage( $e2 ) .
56 "\nBacktrace:\n" . self
::getRedactedTraceAsString( $e2 );
58 $message .= "Exception caught inside exception handler.\n\n" .
59 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
60 "to show detailed debugging information.";
66 self
::printError( $message );
68 echo nl2br( htmlspecialchars( $message ) ) . "\n";
72 $message = "Unexpected non-MediaWiki exception encountered, of type \"" .
73 get_class( $e ) . "\"";
75 if ( $wgShowExceptionDetails ) {
76 $message .= "\n" . MWExceptionHandler
::getLogMessage( $e ) . "\nBacktrace:\n" .
77 self
::getRedactedTraceAsString( $e ) . "\n";
81 self
::printError( $message );
83 echo nl2br( htmlspecialchars( $message ) ) . "\n";
89 * Print a message, if possible to STDERR.
90 * Use this in command line mode only (see isCommandLine)
92 * @param string $message Failure text
94 public static function printError( $message ) {
95 # NOTE: STDERR may not be available, especially if php-cgi is used from the
96 # command line (bug #15602). Try to produce meaningful output anyway. Using
97 # echo may corrupt output to STDOUT though.
98 if ( defined( 'STDERR' ) ) {
99 fwrite( STDERR
, $message );
106 * If there are any open database transactions, roll them back and log
107 * the stack trace of the exception that should have been caught so the
108 * transaction could be aborted properly.
110 * @param Exception $e
112 public static function rollbackMasterChangesAndLog( Exception
$e ) {
113 $factory = wfGetLBFactory();
114 if ( $factory->hasMasterChanges() ) {
115 wfDebugLog( 'Bug56269',
116 'Exception thrown with an uncommited database transaction: ' .
117 MWExceptionHandler
::getLogMessage( $e ) . "\n" .
118 $e->getTraceAsString()
120 $factory->rollbackMasterChanges();
125 * Exception handler which simulates the appropriate catch() handling:
129 * } catch ( MWException $e ) {
131 * } catch ( Exception $e ) {
132 * echo $e->__toString();
134 * @param Exception $e
136 public static function handle( $e ) {
137 global $wgFullyInitialised;
139 self
::rollbackMasterChangesAndLog( $e );
144 if ( $wgFullyInitialised ) {
146 // uses $wgRequest, hence the $wgFullyInitialised condition
147 wfLogProfilingData();
148 } catch ( Exception
$e ) {
152 // Exit value should be nonzero for the benefit of shell jobs
157 * Generate a string representation of an exception's stack trace
159 * Like Exception::getTraceAsString, but replaces argument values with
160 * argument type or class name.
162 * @param Exception $e
165 public static function getRedactedTraceAsString( Exception
$e ) {
168 foreach ( self
::getRedactedTrace( $e ) as $level => $frame ) {
169 if ( isset( $frame['file'] ) && isset( $frame['line'] ) ) {
170 $text .= "#{$level} {$frame['file']}({$frame['line']}): ";
172 // 'file' and 'line' are unset for calls via call_user_func (bug 55634)
173 // This matches behaviour of Exception::getTraceAsString to instead
174 // display "[internal function]".
175 $text .= "#{$level} [internal function]: ";
178 if ( isset( $frame['class'] ) ) {
179 $text .= $frame['class'] . $frame['type'] . $frame['function'];
181 $text .= $frame['function'];
184 if ( isset( $frame['args'] ) ) {
185 $text .= '(' . implode( ', ', $frame['args'] ) . ")\n";
192 $text .= "#{$level} {main}";
198 * Return a copy of an exception's backtrace as an array.
200 * Like Exception::getTrace, but replaces each element in each frame's
201 * argument array with the name of its class (if the element is an object)
202 * or its type (if the element is a PHP primitive).
205 * @param Exception $e
208 public static function getRedactedTrace( Exception
$e ) {
209 return array_map( function ( $frame ) {
210 if ( isset( $frame['args'] ) ) {
211 $frame['args'] = array_map( function ( $arg ) {
212 return is_object( $arg ) ?
get_class( $arg ) : gettype( $arg );
220 * Get the ID for this error.
222 * The ID is saved so that one can match the one output to the user (when
223 * $wgShowExceptionDetails is set to false), to the entry in the debug log.
226 * @param Exception $e
229 public static function getLogId( Exception
$e ) {
230 if ( !isset( $e->_mwLogId
) ) {
231 $e->_mwLogId
= wfRandomString( 8 );
237 * If the exception occurred in the course of responding to a request,
238 * returns the requested URL. Otherwise, returns false.
241 * @return string|bool
243 public static function getURL() {
245 if ( !isset( $wgRequest ) ||
$wgRequest instanceof FauxRequest
) {
248 return $wgRequest->getRequestURL();
252 * Return the requested URL and point to file and line number from which the
253 * exception occurred.
256 * @param Exception $e
259 public static function getLogMessage( Exception
$e ) {
260 $id = self
::getLogId( $e );
261 $file = $e->getFile();
262 $line = $e->getLine();
263 $message = $e->getMessage();
264 $url = self
::getURL() ?
: '[no req]';
266 return "[$id] $url Exception from line $line of $file: $message";
270 * Serialize an Exception object to JSON.
272 * The JSON object will have keys 'id', 'file', 'line', 'message', and
273 * 'url'. These keys map to string values, with the exception of 'line',
274 * which is a number, and 'url', which may be either a string URL or or
275 * null if the exception did not occur in the context of serving a web
278 * If $wgLogExceptionBacktrace is true, it will also have a 'backtrace'
279 * key, mapped to the array return value of Exception::getTrace, but with
280 * each element in each frame's "args" array (if set) replaced with the
281 * argument's class name (if the argument is an object) or type name (if
282 * the argument is a PHP primitive).
284 * @par Sample JSON record ($wgLogExceptionBacktrace = false):
288 * "file": "/var/www/mediawiki/includes/cache/MessageCache.php",
290 * "message": "Non-string key given",
291 * "url": "/wiki/Main_Page"
295 * @par Sample JSON record ($wgLogExceptionBacktrace = true):
299 * "file": "/vagrant/mediawiki/includes/cache/MessageCache.php",
301 * "message": "Non-string key given",
302 * "url": "/wiki/Main_Page",
304 * "file": "/vagrant/mediawiki/extensions/VisualEditor/VisualEditor.hooks.php",
307 * "class": "MessageCache",
315 * @param Exception $e
316 * @param bool $pretty Add non-significant whitespace to improve readability (default: false).
317 * @param int $escaping Bitfield consisting of FormatJson::.*_OK class constants.
318 * @return string|bool JSON string if successful; false upon failure
320 public static function jsonSerializeException( Exception
$e, $pretty = false, $escaping = 0 ) {
321 global $wgLogExceptionBacktrace;
323 $exceptionData = array(
324 'id' => self
::getLogId( $e ),
325 'file' => $e->getFile(),
326 'line' => $e->getLine(),
327 'message' => $e->getMessage(),
330 // Because MediaWiki is first and foremost a web application, we set a
331 // 'url' key unconditionally, but set it to null if the exception does
332 // not occur in the context of a web request, as a way of making that
333 // fact visible and explicit.
334 $exceptionData['url'] = self
::getURL() ?
: null;
336 if ( $wgLogExceptionBacktrace ) {
337 // Argument values may not be serializable, so redact them.
338 $exceptionData['backtrace'] = self
::getRedactedTrace( $e );
341 return FormatJson
::encode( $exceptionData, $pretty, $escaping );
345 * Log an exception to the exception log (if enabled).
347 * This method must not assume the exception is an MWException,
348 * it is also used to handle PHP errors or errors from other libraries.
351 * @param Exception $e
353 public static function logException( Exception
$e ) {
354 global $wgLogExceptionBacktrace;
356 if ( !( $e instanceof MWException
) ||
$e->isLoggable() ) {
357 $log = self
::getLogMessage( $e );
358 if ( $wgLogExceptionBacktrace ) {
359 wfDebugLog( 'exception', $log . "\n" . $e->getTraceAsString() );
361 wfDebugLog( 'exception', $log );
364 $json = self
::jsonSerializeException( $e, false, FormatJson
::ALL_OK
);
365 if ( $json !== false ) {
366 wfDebugLog( 'exception-json', $json, 'private' );