Commit 6fcac324 by Qiang Xue

error handling cleanup.

parent 5b357d2e
......@@ -29,6 +29,11 @@ defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL', 0);
* This constant defines the framework installation directory.
*/
defined('YII_PATH') or define('YII_PATH', __DIR__);
/**
* This constant defines whether error handling should be enabled. Defaults to true.
*/
defined('YII_ENABLE_ERROR_HANDLER') or define('YII_ENABLE_ERROR_HANDLER', true);
/**
* YiiBase is the core helper class for the Yii framework.
......
......@@ -11,7 +11,6 @@ namespace yii\base;
use Yii;
use yii\util\FileHelper;
use yii\base\InvalidCallException;
/**
* Application is the base class for all application classes.
......@@ -76,11 +75,9 @@ class Application extends Module
*/
public $sourceLanguage = 'en_us';
/**
* @var array IDs of application components that need to be loaded when the application starts.
* The default value is `array('errorHandler')`, which loads the [[errorHandler]] component
* to ensure errors and exceptions can be handled nicely.
* @var array IDs of the components that need to be loaded when the application starts.
*/
public $preload = array('errorHandler');
public $preload = array();
/**
* @var Controller the currently active controller instance
*/
......@@ -110,8 +107,15 @@ class Application extends Module
Yii::$application = $this;
$this->id = $id;
$this->setBasePath($basePath);
if (YII_ENABLE_ERROR_HANDLER) {
set_exception_handler(array($this, 'handleException'));
set_error_handler(array($this, 'handleError'), error_reporting());
}
$this->registerDefaultAliases();
$this->registerCoreComponents();
Component::__construct($config);
}
......@@ -253,61 +257,61 @@ class Application extends Module
date_default_timezone_set($value);
}
// /**
// * Returns the security manager component.
// * @return SecurityManager the security manager application component.
// */
// public function getSecurityManager()
// {
// return $this->getComponent('securityManager');
// }
//
// /**
// * Returns the locale instance.
// * @param string $localeID the locale ID (e.g. en_US). If null, the {@link getLanguage application language ID} will be used.
// * @return CLocale the locale instance
// */
// public function getLocale($localeID = null)
// {
// return CLocale::getInstance($localeID === null ? $this->getLanguage() : $localeID);
// }
//
// /**
// * @return CNumberFormatter the locale-dependent number formatter.
// * The current {@link getLocale application locale} will be used.
// */
// public function getNumberFormatter()
// {
// return $this->getLocale()->getNumberFormatter();
// }
//
// /**
// * Returns the locale-dependent date formatter.
// * @return CDateFormatter the locale-dependent date formatter.
// * The current {@link getLocale application locale} will be used.
// */
// public function getDateFormatter()
// {
// return $this->getLocale()->getDateFormatter();
// }
//
// /**
// * Returns the core message translations component.
// * @return \yii\i18n\MessageSource the core message translations
// */
// public function getCoreMessages()
// {
// return $this->getComponent('coreMessages');
// }
//
// /**
// * Returns the application message translations component.
// * @return \yii\i18n\MessageSource the application message translations
// */
// public function getMessages()
// {
// return $this->getComponent('messages');
// }
// /**
// * Returns the security manager component.
// * @return SecurityManager the security manager application component.
// */
// public function getSecurityManager()
// {
// return $this->getComponent('securityManager');
// }
//
// /**
// * Returns the locale instance.
// * @param string $localeID the locale ID (e.g. en_US). If null, the {@link getLanguage application language ID} will be used.
// * @return CLocale the locale instance
// */
// public function getLocale($localeID = null)
// {
// return CLocale::getInstance($localeID === null ? $this->getLanguage() : $localeID);
// }
//
// /**
// * @return CNumberFormatter the locale-dependent number formatter.
// * The current {@link getLocale application locale} will be used.
// */
// public function getNumberFormatter()
// {
// return $this->getLocale()->getNumberFormatter();
// }
//
// /**
// * Returns the locale-dependent date formatter.
// * @return CDateFormatter the locale-dependent date formatter.
// * The current {@link getLocale application locale} will be used.
// */
// public function getDateFormatter()
// {
// return $this->getLocale()->getDateFormatter();
// }
//
// /**
// * Returns the core message translations component.
// * @return \yii\i18n\MessageSource the core message translations
// */
// public function getCoreMessages()
// {
// return $this->getComponent('coreMessages');
// }
//
// /**
// * Returns the application message translations component.
// * @return \yii\i18n\MessageSource the application message translations
// */
// public function getMessages()
// {
// return $this->getComponent('messages');
// }
/**
* Returns the database connection component.
......@@ -390,4 +394,73 @@ class Application extends Module
),
));
}
/**
* Handles PHP execution errors such as warnings, notices.
*
* This method is used as a PHP error handler. It will simply raise an `ErrorException`.
*
* @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
* @throws \ErrorException the error exception
*/
public function handleError($code, $message, $file, $line)
{
if (error_reporting() !== 0) {
throw new \ErrorException($message, 0, $code, $file, $line);
}
}
/**
* Handles uncaught PHP exceptions.
*
* This method is implemented as a PHP exception handler. It requires
* that constant YII_ENABLE_ERROR_HANDLER be defined true.
*
* @param \Exception $exception exception that is not caught
*/
public function handleException($exception)
{
// disable error capturing to avoid recursive errors while handling exceptions
restore_error_handler();
restore_exception_handler();
try {
$this->logException($exception);
if (($handler = $this->getErrorHandler()) !== null) {
$handler->handle($exception);
} else {
$message = YII_DEBUG ? (string)$exception : 'Error: ' . $exception->getMessage() . "\n";
echo PHP_SAPI === 'cli' ? $message : '<pre>' . $message . '</pre>';
}
$this->end(1);
} catch(\Exception $e) {
// exception could be thrown in end() or ErrorHandler::handle()
$msg = (string)$e;
$msg .= "\nPrevious exception:\n";
$msg .= (string)$exception;
$msg .= "\n\$_SERVER = " . var_export($_SERVER, true);
error_log($msg);
exit(1);
}
}
// todo: to be polished
protected function logException($exception)
{
$category = get_class($exception);
if ($exception instanceof HttpException) {
/** @var $exception HttpException */
$category .= '\\' . $exception->statusCode;
} elseif ($exception instanceof \ErrorException) {
/** @var $exception \ErrorException */
$category .= '\\' . $exception->getSeverity();
}
Yii::error((string)$exception, $category);
}
}
......@@ -54,66 +54,18 @@ class ErrorHandler extends Component
public $exception;
public function init()
{
set_exception_handler(array($this, 'handleException'));
set_error_handler(array($this, 'handleError'), error_reporting());
}
/**
* Handles PHP execution errors such as warnings, notices.
*
* This method is used as a PHP error handler. It will simply raise an `ErrorException`.
*
* @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
* @throws \ErrorException the error exception
*/
public function handleError($code, $message, $file, $line)
{
if(error_reporting()!==0) {
throw new \ErrorException($message, 0, $code, $file, $line);
}
}
/**
* @param \Exception $exception
*/
public function handleException($exception)
public function handle($exception)
{
// disable error capturing to avoid recursive errors while handling exceptions
restore_error_handler();
restore_exception_handler();
$this->exception = $exception;
$this->logException($exception);
if ($this->discardExistingOutput) {
$this->clearOutput();
}
try {
$this->render($exception);
} catch (\Exception $e) {
// use the most primitive way to display exception thrown in the error view
$this->renderAsText($e);
}
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);
}
}
protected function render($exception)
......@@ -282,19 +234,6 @@ class ErrorHandler extends Component
return htmlspecialchars($text, ENT_QUOTES, \Yii::$application->charset);
}
public function logException($exception)
{
$category = get_class($exception);
if ($exception instanceof HttpException) {
/** @var $exception HttpException */
$category .= '\\' . $exception->statusCode;
} elseif ($exception instanceof \ErrorException) {
/** @var $exception \ErrorException */
$category .= '\\' . $exception->getSeverity();
}
\Yii::error((string)$exception, $category);
}
public function clearOutput()
{
// the following manual level counting is to deal with zlib.output_compression set to On
......
......@@ -85,7 +85,6 @@ class Application extends \yii\base\Application
* Processes the request.
* The request is represented in terms of a controller route and action parameters.
* @return integer the exit status of the controller action (0 means normal, non-zero values mean abnormal)
* @throws Exception if the route cannot be resolved into a controller
*/
public function processRequest()
{
......@@ -99,7 +98,6 @@ class Application extends \yii\base\Application
}
}
/**
* Runs a controller action specified by a route.
* This method parses the specified route and creates the corresponding child module(s), controller and action
......@@ -108,7 +106,6 @@ class Application extends \yii\base\Application
* @param string $route the route that specifies the action.
* @param array $params the parameters to be passed to the action
* @return integer the status code returned by the action execution. 0 means normal, and other values mean abnormal.
* @throws InvalidRouteException if the requested route cannot be resolved into an action successfully
*/
public function runAction($route, $params = array())
{
......@@ -151,4 +148,9 @@ class Application extends \yii\base\Application
),
));
}
public function usageError($message)
{
}
}
......@@ -103,7 +103,7 @@ class Controller extends \yii\base\Controller
}
}
public function error($message)
public function usageError($message)
{
echo "\nError: $message\n";
Yii::$application->end(1);
......
......@@ -55,7 +55,7 @@ class HelpController extends Controller
} else {
$result = \Yii::$application->createController($args[0]);
if ($result === false) {
echo "\nError: no help for unknown command \"{$args[0]}\".\n";
echo "Error: no help for unknown command \"{$args[0]}\".\n";
return 1;
}
......@@ -213,7 +213,7 @@ class HelpController extends Controller
{
$action = $controller->createAction($actionID);
if ($action === null) {
echo "Unknown sub-command: " . $controller->getUniqueId() . "/$actionID\n";
echo 'Error: no help for unknown sub-command "' . $controller->getUniqueId() . "/$actionID\".\n";
return 1;
}
if ($action instanceof InlineAction) {
......
<?php
define('YII_ENABLE_EXCEPTION_HANDLER', false);
define('YII_ENABLE_ERROR_HANDLER', false);
define('YII_DEBUG', true);
$_SERVER['SCRIPT_NAME'] = '/' . __DIR__;
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment