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 * Exception handler which simulates the appropriate catch() handling:
109 * } catch ( MWException $e ) {
111 * } catch ( Exception $e ) {
112 * echo $e->__toString();
115 public static function handle( $e ) {
116 global $wgFullyInitialised;
121 if ( $wgFullyInitialised ) {
123 // uses $wgRequest, hence the $wgFullyInitialised condition
124 wfLogProfilingData();
125 } catch ( Exception
$e ) {
129 // Exit value should be nonzero for the benefit of shell jobs
134 * Generate a string representation of an exception's stack trace
136 * Like Exception::getTraceAsString, but replaces argument values with
137 * argument type or class name.
139 * @param Exception $e
142 public static function getRedactedTraceAsString( Exception
$e ) {
145 foreach ( self
::getRedactedTrace( $e ) as $level => $frame ) {
146 if ( isset( $frame['file'] ) && isset( $frame['line'] ) ) {
147 $text .= "#{$level} {$frame['file']}({$frame['line']}): ";
149 // 'file' and 'line' are unset for calls via call_user_func (bug 55634)
150 // This matches behaviour of Exception::getTraceAsString to instead
151 // display "[internal function]".
152 $text .= "#{$level} [internal function]: ";
155 if ( isset( $frame['class'] ) ) {
156 $text .= $frame['class'] . $frame['type'] . $frame['function'];
158 $text .= $frame['function'];
161 if ( isset( $frame['args'] ) ) {
162 $text .= '(' . implode( ', ', $frame['args'] ) . ")\n";
169 $text .= "#{$level} {main}";
175 * Return a copy of an exception's backtrace as an array.
177 * Like Exception::getTrace, but replaces each element in each frame's
178 * argument array with the name of its class (if the element is an object)
179 * or its type (if the element is a PHP primitive).
182 * @param Exception $e
185 public static function getRedactedTrace( Exception
$e ) {
186 return array_map( function ( $frame ) {
187 if ( isset( $frame['args'] ) ) {
188 $frame['args'] = array_map( function ( $arg ) {
189 return is_object( $arg ) ?
get_class( $arg ) : gettype( $arg );
197 * Get the ID for this error.
199 * The ID is saved so that one can match the one output to the user (when
200 * $wgShowExceptionDetails is set to false), to the entry in the debug log.
203 * @param Exception $e
206 public static function getLogId( Exception
$e ) {
207 if ( !isset( $e->_mwLogId
) ) {
208 $e->_mwLogId
= wfRandomString( 8 );
214 * If the exception occurred in the course of responding to a request,
215 * returns the requested URL. Otherwise, returns false.
218 * @return string|bool
220 public static function getURL() {
222 if ( !isset( $wgRequest ) ||
$wgRequest instanceof FauxRequest
) {
225 return $wgRequest->getRequestURL();
229 * Return the requested URL and point to file and line number from which the
230 * exception occurred.
233 * @param Exception $e
236 public static function getLogMessage( Exception
$e ) {
237 $id = self
::getLogId( $e );
238 $file = $e->getFile();
239 $line = $e->getLine();
240 $message = $e->getMessage();
241 $url = self
::getURL() ?
: '[no req]';
243 return "[$id] $url Exception from line $line of $file: $message";
247 * Serialize an Exception object to JSON.
249 * The JSON object will have keys 'id', 'file', 'line', 'message', and
250 * 'url'. These keys map to string values, with the exception of 'line',
251 * which is a number, and 'url', which may be either a string URL or or
252 * null if the exception did not occur in the context of serving a web
255 * If $wgLogExceptionBacktrace is true, it will also have a 'backtrace'
256 * key, mapped to the array return value of Exception::getTrace, but with
257 * each element in each frame's "args" array (if set) replaced with the
258 * argument's class name (if the argument is an object) or type name (if
259 * the argument is a PHP primitive).
261 * @par Sample JSON record ($wgLogExceptionBacktrace = false):
265 * "file": "/var/www/mediawiki/includes/cache/MessageCache.php",
267 * "message": "Non-string key given",
268 * "url": "/wiki/Main_Page"
272 * @par Sample JSON record ($wgLogExceptionBacktrace = true):
276 * "file": "/vagrant/mediawiki/includes/cache/MessageCache.php",
278 * "message": "Non-string key given",
279 * "url": "/wiki/Main_Page",
281 * "file": "/vagrant/mediawiki/extensions/VisualEditor/VisualEditor.hooks.php",
284 * "class": "MessageCache",
292 * @param Exception $e
293 * @param bool $pretty Add non-significant whitespace to improve readability (default: false).
294 * @param int $escaping Bitfield consisting of FormatJson::.*_OK class constants.
295 * @return string|bool: JSON string if successful; false upon failure
297 public static function jsonSerializeException( Exception
$e, $pretty = false, $escaping = 0 ) {
298 global $wgLogExceptionBacktrace;
300 $exceptionData = array(
301 'id' => self
::getLogId( $e ),
302 'file' => $e->getFile(),
303 'line' => $e->getLine(),
304 'message' => $e->getMessage(),
307 // Because MediaWiki is first and foremost a web application, we set a
308 // 'url' key unconditionally, but set it to null if the exception does
309 // not occur in the context of a web request, as a way of making that
310 // fact visible and explicit.
311 $exceptionData['url'] = self
::getURL() ?
: null;
313 if ( $wgLogExceptionBacktrace ) {
314 // Argument values may not be serializable, so redact them.
315 $exceptionData['backtrace'] = self
::getRedactedTrace( $e );
318 return FormatJson
::encode( $exceptionData, $pretty, $escaping );
322 * Log an exception to the exception log (if enabled).
324 * This method must not assume the exception is an MWException,
325 * it is also used to handle PHP errors or errors from other libraries.
328 * @param Exception $e
330 public static function logException( Exception
$e ) {
331 global $wgLogExceptionBacktrace;
333 if ( !( $e instanceof MWException
) ||
$e->isLoggable() ) {
334 $log = self
::getLogMessage( $e );
335 if ( $wgLogExceptionBacktrace ) {
336 wfDebugLog( 'exception', $log . "\n" . $e->getTraceAsString() );
338 wfDebugLog( 'exception', $log );
341 $json = self
::jsonSerializeException( $e, false, FormatJson
::ALL_OK
);
342 if ( $json !== false ) {
343 wfDebugLog( 'exception-json', $json, 'private' );