ErrorHandler.php 9.67 KB
Newer Older
Qiang Xue committed
1 2
<?php
/**
Qiang Xue committed
3
 * ErrorHandler class file.
Qiang Xue committed
4 5
 *
 * @link http://www.yiiframework.com/
Qiang Xue committed
6
 * @copyright Copyright &copy; 2008 Yii Software LLC
Qiang Xue committed
7 8 9
 * @license http://www.yiiframework.com/license/
 */

Qiang Xue committed
10
namespace yii\base;
Qiang Xue committed
11 12

/**
Qiang Xue committed
13
 * ErrorHandler handles uncaught PHP errors and exceptions.
Qiang Xue committed
14
 *
Qiang Xue committed
15 16 17
 * ErrorHandler displays these errors using appropriate views based on the
 * nature of the errors and the mode the application runs at.
 *
Qiang Xue committed
18
 * @author Qiang Xue <qiang.xue@gmail.com>
Qiang Xue committed
19
 * @since 2.0
Qiang Xue committed
20
 */
21 22
use yii\util\VarDumper;

Qiang Xue committed
23
class ErrorHandler extends ApplicationComponent
Qiang Xue committed
24 25 26 27
{
	/**
	 * @var integer maximum number of source code lines to be displayed. Defaults to 25.
	 */
Qiang Xue committed
28
	public $maxSourceLines = 25;
Qiang Xue committed
29 30 31 32 33 34 35
	/**
	 * @var integer maximum number of trace source code lines to be displayed. Defaults to 10.
	 */
	public $maxTraceSourceLines = 10;
	/**
	 * @var boolean whether to discard any existing page output before error display. Defaults to true.
	 */
Qiang Xue committed
36
	public $discardExistingOutput = true;
Qiang Xue committed
37 38
	/**
	 * @var string the route (eg 'site/error') to the controller action that will be used to display external errors.
Qiang Xue committed
39
	 * Inside the action, it can retrieve the error information by \Yii::$application->errorHandler->error.
Qiang Xue committed
40
	 * This property defaults to null, meaning ErrorHandler will handle the error display.
Qiang Xue committed
41 42
	 */
	public $errorAction;
Qiang Xue committed
43 44 45
	/**
	 * @var string the path of the view file for rendering exceptions
	 */
Qiang Xue committed
46
	public $exceptionView = '@yii/views/exception.php';
Qiang Xue committed
47 48 49
	/**
	 * @var string the path of the view file for rendering errors
	 */
Qiang Xue committed
50 51 52 53
	public $errorView = '@yii/views/error.php';
	/**
	 * @var \Exception the exception that is being handled currently
	 */
Qiang Xue committed
54
	public $exception;
Qiang Xue committed
55 56 57 58 59
	/**
	 * @var boolean whether to log errors also using error_log(). Defaults to true.
	 * Note that errors captured by the error handler are always logged by [[\Yii::error()]].
	 */
	public $logErrors = true;
Qiang Xue committed
60 61 62 63 64 65 66

	public function init()
	{
		set_exception_handler(array($this, 'handleException'));
		set_error_handler(array($this, 'handleError'), error_reporting());
	}

Qiang Xue committed
67 68 69
	/**
	 * Handles PHP execution errors such as warnings, notices.
	 *
Qiang Xue committed
70
	 * This method is used as a PHP error handler. It will simply raise an `ErrorException`.
Qiang Xue committed
71 72 73 74 75
	 *
	 * @param integer $code the level of the error raised
	 * @param string $message the error message
	 * @param string $file the filename that the error was raised in
	 * @param integer $line the line number the error was raised at
Qiang Xue committed
76
	 * @throws \ErrorException the error exception
Qiang Xue committed
77 78
	 */
	public function handleError($code, $message, $file, $line)
Qiang Xue committed
79
	{
80 81 82
		if(error_reporting()!==0) {
			throw new \ErrorException($message, 0, $code, $file, $line);
		}
Qiang Xue committed
83
	}
Qiang Xue committed
84 85

	/**
Qiang Xue committed
86
	 * @param \Exception $exception
Qiang Xue committed
87
	 */
Qiang Xue committed
88
	public function handleException($exception)
Qiang Xue committed
89
	{
Qiang Xue committed
90
		// disable error capturing to avoid recursive errors while handling exceptions
Qiang Xue committed
91 92 93
		restore_error_handler();
		restore_exception_handler();

Qiang Xue committed
94
		$this->exception = $exception;
Qiang Xue committed
95
		$this->logException($exception);
Qiang Xue committed
96

Qiang Xue committed
97 98 99 100
		if ($this->discardExistingOutput) {
			$this->clearOutput();
		}

Qiang Xue committed
101 102 103 104 105 106
		try {
			$this->render($exception);
		} catch (\Exception $e) {
			// use the most primitive way to display exception thrown in the error view
			$this->renderAsText($e);
		}
Qiang Xue committed
107 108 109 110 111 112 113 114 115 116 117 118 119 120


		try {
			\Yii::$application->end(1);
		} catch (Exception $e2) {
			// use the most primitive way to log error occurred in end()
			$msg = get_class($e2) . ': ' . $e2->getMessage() . ' (' . $e2->getFile() . ':' . $e2->getLine() . ")\n";
			$msg .= $e2->getTraceAsString() . "\n";
			$msg .= "Previous error:\n";
			$msg .= $e2->getTraceAsString() . "\n";
			$msg .= '$_SERVER=' . var_export($_SERVER, true);
			error_log($msg);
			exit(1);
		}
Qiang Xue committed
121 122
	}

Qiang Xue committed
123
	protected function render($exception)
Qiang Xue committed
124
	{
Qiang Xue committed
125 126 127 128 129 130 131 132 133
		if ($this->errorAction !== null) {
			\Yii::$application->runController($this->errorAction);
		} elseif (\Yii::$application instanceof \yii\web\Application) {
			if (!headers_sent()) {
				$errorCode = $exception instanceof HttpException ? $exception->statusCode : 500;
				header("HTTP/1.0 $errorCode " . get_class($exception));
			}
			if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') {
				$this->renderAsText($exception);
Qiang Xue committed
134
			} else {
Qiang Xue committed
135
				$this->renderAsHtml($exception);
Qiang Xue committed
136
			}
Qiang Xue committed
137 138
		} else {
			$this->renderAsText($exception);
Qiang Xue committed
139 140 141 142
		}
	}

	/**
Qiang Xue committed
143 144
	 * Returns server and Yii version information.
	 * @return string server version information.
Qiang Xue committed
145
	 */
Qiang Xue committed
146
	public function getVersionInfo()
Qiang Xue committed
147
	{
Qiang Xue committed
148 149 150
		$version = '<a href="http://www.yiiframework.com/">Yii Framework</a>/' . \Yii::getVersion();
		if (isset($_SERVER['SERVER_SOFTWARE'])) {
			$version = $_SERVER['SERVER_SOFTWARE'] . ' ' . $version;
Qiang Xue committed
151 152 153 154 155 156 157 158 159 160
		}
		return $version;
	}

	/**
	 * Converts arguments array to its string representation
	 *
	 * @param array $args arguments array to be converted
	 * @return string string representation of the arguments array
	 */
Qiang Xue committed
161
	public function argumentsToString($args)
Qiang Xue committed
162
	{
Qiang Xue committed
163
		$isAssoc = $args !== array_values($args);
Qiang Xue committed
164 165
		$count = 0;
		foreach ($args as $key => $value) {
Qiang Xue committed
166
			$count++;
Qiang Xue committed
167
			if ($count >= 5) {
Qiang Xue committed
168
				if ($count > 5) {
Qiang Xue committed
169
					unset($args[$key]);
Qiang Xue committed
170
				} else {
Qiang Xue committed
171
					$args[$key] = '...';
Qiang Xue committed
172
				}
Qiang Xue committed
173 174 175
				continue;
			}

Qiang Xue committed
176
			if (is_object($value)) {
Qiang Xue committed
177
				$args[$key] = get_class($value);
Qiang Xue committed
178
			} elseif (is_bool($value)) {
Qiang Xue committed
179
				$args[$key] = $value ? 'true' : 'false';
Qiang Xue committed
180 181
			} elseif (is_string($value)) {
				if (strlen($value) > 64) {
Qiang Xue committed
182
					$args[$key] = '"' . substr($value, 0, 64) . '..."';
Qiang Xue committed
183
				} else {
Qiang Xue committed
184
					$args[$key] = '"' . $value . '"';
Qiang Xue committed
185 186
				}
			} elseif (is_array($value)) {
Qiang Xue committed
187
				$args[$key] = 'array(' . $this->argumentsToString($value) . ')';
Qiang Xue committed
188
			} elseif ($value === null) {
Qiang Xue committed
189
				$args[$key] = 'null';
Qiang Xue committed
190
			} elseif (is_resource($value)) {
Qiang Xue committed
191
				$args[$key] = 'resource';
Qiang Xue committed
192
			}
Qiang Xue committed
193

Qiang Xue committed
194 195
			if (is_string($key)) {
				$args[$key] = '"' . $key . '" => ' . $args[$key];
Qiang Xue committed
196
			} elseif ($isAssoc) {
Qiang Xue committed
197
				$args[$key] = $key . ' => ' . $args[$key];
Qiang Xue committed
198 199
			}
		}
Qiang Xue committed
200
		return implode(', ', $args);
Qiang Xue committed
201 202 203 204 205 206 207
	}

	/**
	 * Returns a value indicating whether the call stack is from application code.
	 * @param array $trace the trace data
	 * @return boolean whether the call stack is from application code.
	 */
Qiang Xue committed
208
	public function isCoreCode($trace)
Qiang Xue committed
209
	{
Qiang Xue committed
210
		if (isset($trace['file'])) {
Qiang Xue committed
211
			return $trace['file'] === 'unknown' || strpos(realpath($trace['file']), YII_PATH . DIRECTORY_SEPARATOR) === 0;
Qiang Xue committed
212 213 214 215 216 217 218 219 220 221
		}
		return false;
	}

	/**
	 * Renders the source code around the error line.
	 * @param string $file source file path
	 * @param integer $errorLine the error line number
	 * @param integer $maxLines maximum number of lines to display
	 */
Qiang Xue committed
222
	public function renderSourceCode($file, $errorLine, $maxLines)
Qiang Xue committed
223
	{
Qiang Xue committed
224
		$errorLine--; // adjust line number to 0-based from 1-based
Qiang Xue committed
225 226 227
		if ($errorLine < 0 || ($lines = @file($file)) === false || ($lineCount = count($lines)) <= $errorLine) {
			return;
		}
Qiang Xue committed
228

Qiang Xue committed
229 230 231 232
		$halfLines = (int)($maxLines / 2);
		$beginLine = $errorLine - $halfLines > 0 ? $errorLine - $halfLines : 0;
		$endLine = $errorLine + $halfLines < $lineCount ? $errorLine + $halfLines : $lineCount - 1;
		$lineNumberWidth = strlen($endLine + 1);
Qiang Xue committed
233

Qiang Xue committed
234
		$output = '';
Qiang Xue committed
235
		for ($i = $beginLine; $i <= $endLine; ++$i) {
Qiang Xue committed
236
			$isErrorLine = $i === $errorLine;
Qiang Xue committed
237 238
			$code = sprintf("<span class=\"ln" . ($isErrorLine ? ' error-ln' : '') . "\">%0{$lineNumberWidth}d</span> %s", $i + 1, $this->htmlEncode(str_replace("\t", '    ', $lines[$i])));
			if (!$isErrorLine) {
Qiang Xue committed
239
				$output .= $code;
Qiang Xue committed
240
			} else {
Qiang Xue committed
241
				$output .= '<span class="error">' . $code . '</span>';
Qiang Xue committed
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
			}
		}
		echo '<div class="code"><pre>' . $output . '</pre></div>';
	}

	public function renderTrace($trace)
	{
		$count = 0;
		echo "<table>\n";
		foreach ($trace as $n => $t) {
			if ($this->isCoreCode($t)) {
				$cssClass = 'core collapsed';
			} elseif (++$count > 3) {
				$cssClass = 'app collapsed';
			} else {
				$cssClass = 'app expanded';
			}
259 260

			$hasCode = isset($t['file']) && $t['file'] !== 'unknown' && is_file($t['file']);
Qiang Xue committed
261 262 263 264 265 266
			echo "<tr class=\"trace $cssClass\"><td class=\"number\">#$n</td><td class=\"content\">";
			echo '<div class="trace-file">';
			if ($hasCode) {
				echo '<div class="plus">+</div><div class="minus">-</div>';
			}
			echo '&nbsp;';
267 268 269
			if(isset($t['file'])) {
				echo $this->htmlEncode($t['file']) . '(' . $t['line'] . '): ';
			}
Qiang Xue committed
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
			if (!empty($t['class'])) {
				echo '<strong>' . $t['class'] . '</strong>' . $t['type'];
			}
			echo '<strong>' . $t['function'] . '</strong>';
			echo '(' . (empty($t['args']) ? '' : $this->htmlEncode($this->argumentsToString($t['args']))) . ')';
			echo '</div>';
			if ($hasCode) {
				$this->renderSourceCode($t['file'], $t['line'], $this->maxTraceSourceLines);
			}
			echo "</td></tr>\n";
		}
		echo '</table>';
	}

	public function htmlEncode($text)
	{
		return htmlspecialchars($text, ENT_QUOTES, \Yii::$application->charset);
	}

	public function logException($exception)
	{
		$category = get_class($exception);
		if ($exception instanceof HttpException) {
Qiang Xue committed
293
			/** @var $exception HttpException */
Qiang Xue committed
294 295
			$category .= '\\' . $exception->statusCode;
		} elseif ($exception instanceof \ErrorException) {
Qiang Xue committed
296
			/** @var $exception \ErrorException */
Qiang Xue committed
297 298 299
			$category .= '\\' . $exception->getSeverity();
		}
		\Yii::error((string)$exception, $category);
Qiang Xue committed
300 301 302
		if ($this->logErrors) {
			error_log($exception);
		}
Qiang Xue committed
303 304 305 306 307 308 309
	}

	public function clearOutput()
	{
		// the following manual level counting is to deal with zlib.output_compression set to On
		for ($level = ob_get_level(); $level > 0; --$level) {
			@ob_end_clean();
Qiang Xue committed
310
		}
Qiang Xue committed
311 312 313
	}

	/**
Qiang Xue committed
314
	 * @param \Exception $exception
Qiang Xue committed
315
	 */
Qiang Xue committed
316
	public function renderAsText($exception)
Qiang Xue committed
317
	{
Qiang Xue committed
318
		if (YII_DEBUG) {
Qiang Xue committed
319
			echo $exception;
Qiang Xue committed
320
		} else {
Qiang Xue committed
321
			echo get_class($exception) . ': ' . $exception->getMessage();
Qiang Xue committed
322 323 324 325 326 327 328 329 330
		}
	}

	/**
	 * @param \Exception $exception
	 */
	public function renderAsHtml($exception)
	{
		$view = new View;
Qiang Xue committed
331
		$view->context = $this;
Qiang Xue committed
332
		$name = !YII_DEBUG || $exception instanceof HttpException ? $this->errorView : $this->exceptionView;
333
		echo $view->render($name, array(
Qiang Xue committed
334 335
			'exception' => $exception,
		));
Qiang Xue committed
336 337
	}
}