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
36 protected static function report( Exception
$e ) {
37 global $wgShowExceptionDetails;
39 $cmdLine = MWException
::isCommandLine();
41 if ( $e instanceof MWException
) {
43 // Try and show the exception prettily, with the normal skin infrastructure
45 } catch ( Exception
$e2 ) {
46 // Exception occurred from within exception handler
47 // Show a simpler error message for the original exception,
48 // don't try to invoke report()
49 $message = "MediaWiki internal error.\n\n";
51 if ( $wgShowExceptionDetails ) {
52 $message .= 'Original exception: ' . self
::getLogMessage( $e ) .
53 "\nBacktrace:\n" . self
::getRedactedTraceAsString( $e ) .
54 "\n\nException caught inside exception handler: " . self
::getLogMessage( $e2 ) .
55 "\nBacktrace:\n" . self
::getRedactedTraceAsString( $e2 );
57 $message .= "Exception caught inside exception handler.\n\n" .
58 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
59 "to show detailed debugging information.";
65 self
::printError( $message );
67 echo nl2br( htmlspecialchars( $message ) ) . "\n";
71 $message = "Unexpected non-MediaWiki exception encountered, of type \"" .
72 get_class( $e ) . "\"";
74 if ( $wgShowExceptionDetails ) {
75 $message .= "\n" . MWExceptionHandler
::getLogMessage( $e ) . "\nBacktrace:\n" .
76 self
::getRedactedTraceAsString( $e ) . "\n";
80 self
::printError( $message );
82 echo nl2br( htmlspecialchars( $message ) ) . "\n";
88 * Print a message, if possible to STDERR.
89 * Use this in command line mode only (see isCommandLine)
91 * @param string $message Failure text
93 public static function printError( $message ) {
94 # NOTE: STDERR may not be available, especially if php-cgi is used from the
95 # command line (bug #15602). Try to produce meaningful output anyway. Using
96 # echo may corrupt output to STDOUT though.
97 if ( defined( 'STDERR' ) ) {
98 fwrite( STDERR
, $message );
105 * If there are any open database transactions, roll them back and log
106 * the stack trace of the exception that should have been caught so the
107 * transaction could be aborted properly.
109 * @param Exception $e
111 public static function rollbackMasterChangesAndLog( Exception
$e ) {
112 $factory = wfGetLBFactory();
113 if ( $factory->hasMasterChanges() ) {
114 wfDebugLog( 'Bug56269',
115 'Exception thrown with an uncommited database transaction: ' .
116 MWExceptionHandler
::getLogMessage( $e ) . "\n" .
117 $e->getTraceAsString()
119 $factory->rollbackMasterChanges();
124 * Exception handler which simulates the appropriate catch() handling:
128 * } catch ( MWException $e ) {
130 * } catch ( Exception $e ) {
131 * echo $e->__toString();
134 public static function handle( $e ) {
135 global $wgFullyInitialised;
137 self
::rollbackMasterChangesAndLog( $e );
142 if ( $wgFullyInitialised ) {
144 // uses $wgRequest, hence the $wgFullyInitialised condition
145 wfLogProfilingData();
146 } catch ( Exception
$e ) {
150 // Exit value should be nonzero for the benefit of shell jobs
155 * Generate a string representation of an exception's stack trace
157 * Like Exception::getTraceAsString, but replaces argument values with
158 * argument type or class name.
160 * @param Exception $e
163 public static function getRedactedTraceAsString( Exception
$e ) {
166 foreach ( self
::getRedactedTrace( $e ) as $level => $frame ) {
167 if ( isset( $frame['file'] ) && isset( $frame['line'] ) ) {
168 $text .= "#{$level} {$frame['file']}({$frame['line']}): ";
170 // 'file' and 'line' are unset for calls via call_user_func (bug 55634)
171 // This matches behaviour of Exception::getTraceAsString to instead
172 // display "[internal function]".
173 $text .= "#{$level} [internal function]: ";
176 if ( isset( $frame['class'] ) ) {
177 $text .= $frame['class'] . $frame['type'] . $frame['function'];
179 $text .= $frame['function'];
182 if ( isset( $frame['args'] ) ) {
183 $text .= '(' . implode( ', ', $frame['args'] ) . ")\n";
190 $text .= "#{$level} {main}";
196 * Return a copy of an exception's backtrace as an array.
198 * Like Exception::getTrace, but replaces each element in each frame's
199 * argument array with the name of its class (if the element is an object)
200 * or its type (if the element is a PHP primitive).
203 * @param Exception $e
206 public static function getRedactedTrace( Exception
$e ) {
207 return array_map( function ( $frame ) {
208 if ( isset( $frame['args'] ) ) {
209 $frame['args'] = array_map( function ( $arg ) {
210 return is_object( $arg ) ?
get_class( $arg ) : gettype( $arg );
218 * Get the ID for this error.
220 * The ID is saved so that one can match the one output to the user (when
221 * $wgShowExceptionDetails is set to false), to the entry in the debug log.
224 * @param Exception $e
227 public static function getLogId( Exception
$e ) {
228 if ( !isset( $e->_mwLogId
) ) {
229 $e->_mwLogId
= wfRandomString( 8 );
235 * If the exception occurred in the course of responding to a request,
236 * returns the requested URL. Otherwise, returns false.
239 * @return string|bool
241 public static function getURL() {
243 if ( !isset( $wgRequest ) ||
$wgRequest instanceof FauxRequest
) {
246 return $wgRequest->getRequestURL();
250 * Return the requested URL and point to file and line number from which the
251 * exception occurred.
254 * @param Exception $e
257 public static function getLogMessage( Exception
$e ) {
258 $id = self
::getLogId( $e );
259 $file = $e->getFile();
260 $line = $e->getLine();
261 $message = $e->getMessage();
262 $url = self
::getURL() ?
: '[no req]';
264 return "[$id] $url Exception from line $line of $file: $message";
268 * Serialize an Exception object to JSON.
270 * The JSON object will have keys 'id', 'file', 'line', 'message', and
271 * 'url'. These keys map to string values, with the exception of 'line',
272 * which is a number, and 'url', which may be either a string URL or or
273 * null if the exception did not occur in the context of serving a web
276 * If $wgLogExceptionBacktrace is true, it will also have a 'backtrace'
277 * key, mapped to the array return value of Exception::getTrace, but with
278 * each element in each frame's "args" array (if set) replaced with the
279 * argument's class name (if the argument is an object) or type name (if
280 * the argument is a PHP primitive).
282 * @par Sample JSON record ($wgLogExceptionBacktrace = false):
286 * "file": "/var/www/mediawiki/includes/cache/MessageCache.php",
288 * "message": "Non-string key given",
289 * "url": "/wiki/Main_Page"
293 * @par Sample JSON record ($wgLogExceptionBacktrace = true):
297 * "file": "/vagrant/mediawiki/includes/cache/MessageCache.php",
299 * "message": "Non-string key given",
300 * "url": "/wiki/Main_Page",
302 * "file": "/vagrant/mediawiki/extensions/VisualEditor/VisualEditor.hooks.php",
305 * "class": "MessageCache",
313 * @param Exception $e
314 * @param bool $pretty Add non-significant whitespace to improve readability (default: false).
315 * @param int $escaping Bitfield consisting of FormatJson::.*_OK class constants.
316 * @return string|bool: JSON string if successful; false upon failure
318 public static function jsonSerializeException( Exception
$e, $pretty = false, $escaping = 0 ) {
319 global $wgLogExceptionBacktrace;
321 $exceptionData = array(
322 'id' => self
::getLogId( $e ),
323 'file' => $e->getFile(),
324 'line' => $e->getLine(),
325 'message' => $e->getMessage(),
328 // Because MediaWiki is first and foremost a web application, we set a
329 // 'url' key unconditionally, but set it to null if the exception does
330 // not occur in the context of a web request, as a way of making that
331 // fact visible and explicit.
332 $exceptionData['url'] = self
::getURL() ?
: null;
334 if ( $wgLogExceptionBacktrace ) {
335 // Argument values may not be serializable, so redact them.
336 $exceptionData['backtrace'] = self
::getRedactedTrace( $e );
339 return FormatJson
::encode( $exceptionData, $pretty, $escaping );
343 * Log an exception to the exception log (if enabled).
345 * This method must not assume the exception is an MWException,
346 * it is also used to handle PHP errors or errors from other libraries.
349 * @param Exception $e
351 public static function logException( Exception
$e ) {
352 global $wgLogExceptionBacktrace;
354 if ( !( $e instanceof MWException
) ||
$e->isLoggable() ) {
355 $log = self
::getLogMessage( $e );
356 if ( $wgLogExceptionBacktrace ) {
357 wfDebugLog( 'exception', $log . "\n" . $e->getTraceAsString() );
359 wfDebugLog( 'exception', $log );
362 $json = self
::jsonSerializeException( $e, false, FormatJson
::ALL_OK
);
363 if ( $json !== false ) {
364 wfDebugLog( 'exception-json', $json, 'private' );