Example explains how to do error and exception handling in the _php of PHP's YII framework

Source: Internet
Author: User
Tags constant error handling exception handling openssl php error yii

Yii has already implemented the exception and the wrong takeover on the CApplication by default, which is implemented through the Set_exception_handler,set_error_handler of PHP. With these two PHP built-in functions, you can improve the maintainability of the program by taking over the exceptions and errors that are not caught in the program. This is critical in large systems, when errors occur, we want to be able to record the relevant details, or even send the alarm immediately, thereby shortening the repair time and improve the stability of the entire system.
By default, Yii assigns exception handling to capplication::handleexception, assigning error handling to Capplication::handleerror, but can be defined by defining Yii_enable_ in the Portal file Exception_handler, Yii_enable_error_handler two constants to false prohibits using YII's exception and error takeover mechanisms.
In the following section, the exceptions and errors are collectively referred to as errors and, if necessary, detailed distinctions are made. The Yii_debug constant (the default is False, which can be set in the entry file) has an important effect on the display of the error message, and in debug mode, the wrong output is the most verbose. Once the program has been put into operation, the Yii_debug should be modified to false.
Whether in debug mode or not, the YII program produces an error that records the relevant error message (Error level errors, classification defaults to application). The difference is that the debug mode displays detailed information directly on the Web page.

CApplication:: HandleError ($code, $message, $file, $line)

The above method implements the relevant logos. Pay special attention to restore_error_handler,restore_exception_handler two functions, if no calls to these two functions, then in the subsequent error processing, when the exception or error again, It also calls CApplication:: HandleError, which may cause a dead loop, so Yii temporarily prohibits the use of CApplication:: HandleError take over subsequent errors and exceptions (using the PHP default error handling mechanism), This ensures that no circular calls are generated.
PHP Error handling what information does PHP record in the log when an error is generated? Error code (that is, PHP's e_error e_warning e_strict e_deprecated) message content (such as Undefined vaiable $ Input) generates the wrong file path generates the wrong line number additional trace backtracking information (this is implemented via Debug_backtrace) Current URL
In addition to logging the corresponding logs, Yii will also follow up on errors (such as breaking the run, displaying error pages, and so on), By default, the wrong processing is delivered to the Cerrorhandler component (but the design is flexible because it can be handled two times by Capplicaton binding the OnError event handler). )。
A cerrorevent (and contains $code, $message, $file, $line several key parameters) is generated and passed to the Cerrorhandler component for processing. The specific is to cerrorhandler::handleerror treatment. The process is mainly to organize the error-related information and display it in a suitable way.
is a DEBUG mode (yii_debug==true) that has a significant impact on the display of error messages. In debug mode we want to display detailed error tracking information, and in production mode we want to show the user a friendly page. Therefore, the error shown here is different, as explained below.
When in debug mode, direct rendering of the exception view shows the error. The following path is searched:

    • protected/views/system/exception.php
    • yii_path/views/exception.php

Obviously, the Views/system directory is not defined in your application by default, so you use the view file from the system framework. The final file included will be the views/exception.php in the Yii framework.

As can be learned from the above analysis, in the debug mode if we want to use the custom exception page (generally do not mean to do), you need to configure file protected/views/system/exception.php, the variable that can be used is $data.
When in non-debug mode, this is done as follows:

If ErrorAction routing information is defined for the ErrorHandler component in the configuration file, it runs directly, otherwise the 2nd step process is performed.
Try loading the error view, search by the following path (the first file to be searched will be used)

    • protected/views/system/zh_cn/error500.php
    • protected/views/system/error500.php
    • protected/views/system/zh_cn/error.php
    • protected/views/system/error.php
    • yii_path/views/zh_cn/error500.php
    • yii_path/views/error500.php
    • yii_path/views/zh_cn/error.php
    • Y ii_path/views/error.php

Exception processing According to the previous analysis, the exception processing mechanism and error handling mechanism similar, will also log, level is error, classified as "exception $EXCEPTIONCLASS", if the Chttpexception class exception, The category name is exception. Chttpexception. $STATUS _code. such as the exception classification of data is called exception. CDBException.

The error event is then cexceptionevent to the ErrorHandler process, and all error messages are passed by the Cexceptionevent object. The processing method is as follows:

In the case of debug mode, the view file is searched in the following order, and the first file to be searched is used

    • protected/views/system/exception.php
    • yii_path/views/exception.php

If it is not in debug mode and the ErrorAction property route is defined for the ErrorHandler component in the configuration file, run, otherwise enter step 3rd.
Try to load the view file in the following order, and the first file to be searched will be used
protected/views/system/zh_cn/error500.phpprotected/views/system/error500.phpprotected/views/system/zh_cn/ error.phpprotected/views/system/error.phpyii_path/views/zh_cn/error500.phpyii_path/views/error500.phpyii_path/ Views/zh_cn/error.phpy ii_path/views/error.php

With the flowchart description, it's clearer: The search view file process is important because it concerns how we can customize the details of the error page, and subsequent flowcharts describe its process in detail.

As you can see from the diagram, the easiest way to do this is to set the ErrorAction property for the ErrorHandler component to specify the route where the error occurred

In general, we are most concerned about the production mode of the error page display problem, through the above analysis, there are two methods available:

Define ErrorAction routing properties for the ErrorHandler component in the configuration file (this should be used preferentially for flexible configuration purposes)
Define any of the following files to implement a custom error page (not recommended)

    • protected/views/system/zh_cn/error500.php
    • protected/views/system/error500.php
    • protected/views/system/zh_cn/error.php
    • protected/views/system/error.php

The 1th way is flexible and controllable, you can specify the view file in the controller, flexible and controllable.

Using the error handler example

Yii\web\errorhandler is registered as a ErrorHandler application component that can be configured in an application configuration similar to the following:

return ['
  components ' => ['
    errorhandler ' => ['
      maxsourcelines ' =>,
    ],
],];

With the code as above, the exception page displays up to 20 source codes.

As mentioned earlier, the error processor converts all non-fatal PHP errors to a fetch exception, which means that you can handle PHP errors using the following code:

Use Yii;
Use yii\base\errorexception;

try {
  10/0
} catch (Errorexception $e) {
  yii::warning ("division by zero.");
}

Execution continues ...

If you want to display an error page telling the user that the request is invalid or cannot be handled, simply throw a yii\web\httpexception exception, such as Yii\web\notfoundhttpexception. The error handler correctly sets the HTTP status code for the response and uses the appropriate Error view page to display the error message.

Use yii\web\notfoundhttpexception;

throw new Notfoundhttpexception ();

Custom error Display

The Yii\web\errorhandler error processor adjusts the error display based on the value of the constant Yii_debug, and when Yii_debug is true (in debug mode), the error processor displays the exception as well as the detailed function call stack and source code line number to help debug when the Yii_ DEBUG is false, and only error messages are displayed to prevent the application of sensitive information from leaking.

Add: If the exception is an inherited Yii\base\userexception, the function call stack information is not displayed, regardless of the yii_debug value, because the error is considered a user error and the developer does not need to fix it.
The Yii\web\errorhandler error processor defaults to displaying errors using two views:

    • @yii/views/errorhandler/error.php: The error message that displays information that does not contain the function call stack is used, and when Yii_debug is false, all errors use that view.
    • @yii/views/errorhandler/exception.php: used when displaying error messages that contain information about the function call stack.

You can configure the Yii\web\errorhandler::errorview and Yii\web\errorhandler::exceptionview properties of the error processor to display the view using a custom error.

Using Error actions

It is more convenient to customize the error display using the specified error action, and to do this, first configure the Yii\web\errorhandler::erroraction property of the ErrorHandler component, similar to the following:

return ['
  components ' => [' ErrorHandler ' => [' erroraction ' => ' site/error '
      ,
    ],
  ]
] ;

The Yii\web\errorhandler::erroraction property uses routing to an action that indicates that an error without displaying the function call stack information is displayed by performing a site/error operation.

The Site/error action can be created as follows:

namespace App\controllers;

Use Yii;
Use Yii\web\controller;

Class Sitecontroller extends Controller
{public
  function actions ()
  {return
    [
      ' ERROR ' =>] [
        ' class ' => ' yii\web\erroraction ',
      ],
    ];
  }


The above code defines an error operation that uses the Yii\web\erroraction class, which renders the error view to display errors.

In addition to using yii\web\erroraction, you can define an error operation using a method similar to the following:

Public Function Actionerror ()
{
  $exception = Yii:: $app->errorhandler->exception;
  if ($exception!== null) {return
    $this->render (' Error ', [' Exception ' => $exception]);
  }

You should now create a view file that is views/site/error.php, in which you can access the following variables defined in the operation if the error action is defined as Yii\web\erroraction:

    • Name: Bad names
    • Message: Error messages
    • Exception: More details of the exception object, such as HTTP status code, error code, error call stack, and so on.

Add: If you use the underlying application template or the Advanced application template, the error action and error view are already defined.

Custom error format

The error handler displays an error based on the format of the response setting, and if the Yii\web\response::format response format is HTML, an error or exception view is used to display the error message, as described in the previous section. For other response formats, the error handler will assign the error message as an array to the Yii\web\response::d ATA Properties, and then convert to the corresponding format, for example, if the response format is JSON, you can see the following response information:

http/1.1 404 Not Found
Date:sun, Mar 2014 05:31:43 GMT
server:apache/2.2.26 (Unix) DAV/2 php/5.4.20 MOD_SSL/2 .2.26 openssl/0.9.8y
transfer-encoding:chunked
content-type:application/json; charset=utf-8

{
  " Name ': ' Not Found Exception ', ' Message
  ': "The requested resource is not Found.",
  "code": 0,
  "status": 404
   }

The Beforesend event that responds to the response component in the application configuration comes from defining the error response format.

return [
  //...
  ] Components ' => ['
    response ' => ['
      class ' => ' Yii\web\response ', ' on beforesend ' =>
      function ($ Event) {
        $response = $event->sender;
        if ($response->data!== null) {
          $response->data = [
            ' success ' => $response->issuccessful,
            ' Data ' => $response->data,
          ];
          $response->statuscode =;
        },
    ],]
  ,]
;

The code above will reformat the error response, similar to the following:

http/1.1 OK
Date:sun, Mar 2014 05:31:43 GMT
server:apache/2.2.26 (Unix) DAV/2 php/5.4.20 Openssl/0.9.8y
transfer-encoding:chunked
content-type:application/json; charset=utf-8

{
  " Success ': false,
  ' data ': {
    ' name ': ' Not Found Exception ',
    ' message ': ' The requested resource is not Found . ",
    " code ": 0,
    " status ": 404
  }
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.