Error Handling

Yii provides a complete error handling framework based on the PHP 5exception mechanism. When the application is created to handle an incominguser request, it registers its handleErrormethod to handle PHP warnings and notices; and it registers itshandleException method to handle uncaughtPHP exceptions. Consequently, if a PHP warning/notice or an uncaughtexception occurs during the application execution, one of the errorhandlers will take over the control and start the necessary error handlingprocedure.

Tip: The registration of error handlers is done in the application's constructor by calling PHP functions set_exception_handler and set_error_handler. If you do not want Yii to handle the errors and exceptions, you may define constant YII_ENABLE_ERROR_HANDLER and YII_ENABLE_EXCEPTION_HANDLER to be false in the entry script.

By default, errorHandler (orexceptionHandler) will raise anonError event (oronException event). If the error (or exception)is not handled by any event handler, it will call for help from theerrorHandler application component.

1. Raising Exceptions

Raising exceptions in Yii is not different from raising a normal PHPexception. One uses the following syntax to raise an exception when needed:

  1. throw new ExceptionClass('ExceptionMessage');

Yii defines two exception classes: CException and CHttpException. Theformer is a generic exception class, while the latter represents anexception that should be displayed to end users. The latter also carries astatusCode property representing an HTTPstatus code. The class of an exception determines how it should bedisplayed, as we will explain next.

Tip: Raising a CHttpException exception is a simple way of reporting errors caused by user misoperation. For example, if the user provides an invalid post ID in the URL, we can simply do the following to show a 404 error (page not found):
  1. // if post ID is invalid
  2. throw new CHttpException(404,'The specified post cannot be found.');

2. Displaying Errors

When an error is forwarded to the CErrorHandler application component,it chooses an appropriate view to display the error. If the error is meantto be displayed to end users, such as a CHttpException, it will use aview named errorXXX, where XXX stands for the HTTP status code (e.g.400, 404, 500). If the error is an internal one and should only bedisplayed to developers, it will use a view named exception. In thelatter case, complete call stack as well as the error line information willbe displayed.

Info: When the application runs in production mode, all errors including those internal ones will be displayed using view errorXXX. This is because the call stack of an error may contain sensitive information. In this case, developers should rely on the error logs to determine what is the real cause of an error.

CErrorHandler searches for the view file corresponding to a view in thefollowing order:

  • WebRoot/themes/ThemeName/views/system: this is the system viewdirectory under the currently active theme.

  • WebRoot/protected/views/system: this is the default system viewdirectory for an application.

  • yii/framework/views: this is the standard system view directoryprovided by the Yii framework.

Therefore, if we want to customize the error display, we can simply createerror view files under the system view directory of our application ortheme. Each view file is a normal PHP script consisting of mainly HTMLcode. For more details, please refer to the default view files under theframework's view directory.

Handling Errors Using an Action

Starting from version 1.0.6, Yii allows using a controller actionto handle the error display work. To do so, we should configure the error handlerin the application configuration as follows:

  1. return array(
  2. ......
  3. 'components'=>array(
  4. 'errorHandler'=>array(
  5. 'errorAction'=>'site/error',
  6. ),
  7. ),
  8. );

In the above, we configure the CErrorHandler::errorAction property to be the routesite/error which refers to the error action in SiteController. We may use a differentroute if needed.

We can write the error action like the following:

  1. public function actionError()
  2. {
  3. if($error=Yii::app()->errorHandler->error)
  4. $this->render('error', $error);
  5. }

In the action, we first retrieve the detailed error information from CErrorHandler::error.If it is not empty, we render the error view together with the error information.The error information returned from CErrorHandler::error is an array with the following fields:

  • code: the HTTP status code (e.g. 403, 500);
  • type: the error type (e.g. CHttpException, PHP Error);
  • message: the error message;
  • file: the name of the PHP script file where the error occurs;
  • line: the line number of the code where the error occurs;
  • trace: the call stack of the error;
  • source: the context source code where the error occurs.
Tip: The reason we check if CErrorHandler::error is empty or not is because the error action may be directly requested by an end user, in which case there is no error. Since we are passing the $error array to the view, it will be automatically expanded to individual variables. As a result, in the view we can access directly the variables such as $code, $type.

3. Message Logging

A message of level error will always be logged when an error occurs. Ifthe error is caused by a PHP warning or notice, the message will be loggedwith category php; if the error is caused by an uncaught exception, thecategory would be exception.ExceptionClassName (for CHttpException itsstatusCode will also be appended to thecategory). One can thus exploit the loggingfeature to monitor errors happened during application execution.

原文: https://www.yiichina.com/doc/guide/1.0/topics.error