From 8ee92fdb8045c9c5dc454c516ea800091a228f30 Mon Sep 17 00:00:00 2001 From: Qiang Xue Date: Sat, 10 Aug 2013 07:32:19 -0400 Subject: [PATCH] Added ErrorAction. --- framework/yii/web/ErrorAction.php | 108 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 framework/yii/web/ErrorAction.php diff --git a/framework/yii/web/ErrorAction.php b/framework/yii/web/ErrorAction.php new file mode 100644 index 0000000..3dd2823 --- /dev/null +++ b/framework/yii/web/ErrorAction.php @@ -0,0 +1,108 @@ + array( + * 'class' => 'yii\web\ErrorAction', + * ), + * ); + * } + * ``` + * + * Then, create a view file for this action. If the route of your error action is `site/error`, then + * the view file should be `views/site/error.php`. In this view file, the following variables are available: + * + * - `$name`: the error name + * - `$message`: the error message + * - `$exception`: the exception being handled + * + * Finally, configure the "errorHandler" application component as follows, + * + * ```php + * 'errorHandler' => array( + * 'errorAction' => 'site/error', + * ) + * ``` + * + * @author Qiang Xue + * @since 2.0 + */ +class ErrorAction extends Action +{ + /** + * @var string the view file to be rendered. If not set, it will take the value of [[id]]. + * That means, if you name the action as "error" in "SiteController", then the view name + * would be "error", and the corresponding view file would be "views/site/error.php". + */ + public $view; + /** + * @var string the name of the error when the exception name cannot be determined. + * Defaults to "Error". + */ + public $defaultName; + /** + * @var string the message to be displayed when the exception message contains sensitive information. + * Defaults to "An internal server error occurred.". + */ + public $defaultMessage; + + + public function run() + { + if (!($exception = Yii::$app->getErrorHandler()->exception)) { + return ''; + } + + if ($exception instanceof HttpException) { + $code = $exception->statusCode; + } else { + $code = $exception->getCode(); + } + if ($exception instanceof Exception) { + $name = $exception->getName(); + } else { + $name = $this->defaultName ?: Yii::t('yii', 'Error'); + } + if ($code) { + $name .= " (#$code)"; + } + + if ($exception instanceof UserException) { + $message = $exception->getMessage(); + } else { + $message = $this->defaultMessage ?: Yii::t('yii', 'An internal server error occurred.'); + } + + if (Yii::$app->getRequest()->getIsAjax()) { + return "$name: $message"; + } else { + return $this->controller->render($this->view ?: $this->id, array( + 'name' => $name, + 'message' => $message, + 'exception' => $exception, + )); + } + } +}