Home > Backend Development > PHP7 > body text

Examples to explain how PHP handles errors and exceptions in the Yii framework

醉折花枝作酒筹
Release: 2023-02-18 07:20:01
forward
1912 people have browsed it

Yii has implemented exception and error takeover on CApplication by default, which is implemented through php's set_exception_handler and set_error_handler. Through these two PHP built-in functions, uncaught exceptions and errors in the program can be taken over, thereby improving the maintainability of the program.

Examples to explain how PHP handles errors and exceptions in the Yii framework

By default, Yii will assign exception handling to CApplication::handleException and error handling to CApplication::handleError, but you can define YII_ENABLE_EXCEPTION_HANDLER in the entry file , the two constants YII_ENABLE_ERROR_HANDLER are false to prohibit the use of Yii's exception and error takeover mechanism.

In the following content, exceptions and errors are collectively referred to as errors, and detailed distinctions will be made if necessary. The YII_DEBUG constant (defaults to false, which can be set in the entry file) has a very important impact on the display of error information. In debug mode, the error output is the most detailed. Once the program is put into operation, YII_DEBUG should be modified to false.

Regardless of whether it is in debug mode or not, when the Yii program generates an error, the relevant error information will be recorded (the error level is error, and the default category is application). The difference is that in debug mode, detailed information will be displayed directly on the web page.

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

The above method implements the relevant logic. Pay special attention to the restore_error_handler and restore_exception_handler functions. If these two functions are not called, then during the subsequent error handling process, when an exception or error occurs again, CApplication:: handleError will be called again, which may cause an infinite loop. Therefore, Yii temporarily prohibits the use of CApplication::handleError to take over subsequent errors and exceptions (using PHP's default error handling mechanism), which ensures that no loop calls will occur.

PHP error handling When an error occurs, what information will PHP record in the log? Error code (i.e. PHP's E_ERROR E_WARNING E_STRICT E_DEPRECATED) Message content (such as Undefined vaiable $input) The file path that generated the error The line number that generated the error Additional tracking backtrace information (this is achieved through debug_backtrace) The current URL

In addition to recording the corresponding logs, Yii will also perform subsequent processing of errors (such as interrupting the operation, displaying error pages, etc.). By default, error processing will be handed over to the CErrorHandler component (but it can be processed by binding the onError event to CApplicaton The device implements secondary takeover of error handling, the design here is very flexible!).

At this time, a CErrorEvent (and containing several key parameters such as $code, $message, $file, and $line) will be generated and passed to the CErrorHandler component for processing. Specifically, it is handled by CErrorHandler::handleError. This process is mainly to organize error-related information and display it in an appropriate way.

Whether it is in debug mode (YII_DEBUG==true) has a great impact on the display of error messages. In debugging mode we want to display detailed error tracking information, while in production mode we want to display a user-friendly page. Therefore, the error display here is different, and the differences are explained below.

When in debug mode, the exception view will be directly rendered to display errors. Will be searched according to the following path:

protected/views/system/exception.php

YII_PATH/views/exception.php

Obviously, it is not in the application by default The views/system directory is defined in, so the view files that come with the system framework will be used. The final included file will be views/exception.php from the Yii framework.

It can be known from the above analysis that if we want to use a custom exception page in debugging mode (generally it may not make much sense), we need to configure the file protected/views/system/exception.php , the variable that can be used is $data.

When in non-debugging mode, the following processing will be done:

If the errorAction routing information is defined for the errorHandler component in the configuration file, run it directly, otherwise execute the step 2 process.

Try to load the error view, search according to the following path (the first searched file 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 handling According to the previous analysis, the exception handling mechanism is similar to the error handling mechanism. Logs will also be recorded. The level is error and the classification is "exception.$EXCEPTIONCLASS". If it is a CHttpException class exception, the classification name is exception. .CHttpException.$STATUS_CODE. For example, the exception classification of data is called exception.CDbException.

Next, the error event CExceptionEvent is handed over to the errorHandler for processing, and all error information is passed by the CExceptionEvent object. The processing method is as follows:

If it is debug mode, the view files are searched in the following order, and the first searched file will be used

protected/views/system/exception.php

YII_PATH/views/exception.php

If it is non-debugging mode and the errorAction attribute route is defined for the errorHandler component in the configuration file, run it, otherwise go to step 3.

Try to load view files in the following order, the first searched file 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
Copy after login

Using the flow chart description, it will be clearer: The process of searching for view files is more important because it Regarding the details of how we customize the error page, the subsequent flow chart describes the process in detail.

Examples to explain how PHP handles errors and exceptions in the Yii framework

As you can see from the picture, the easiest way is to set the errorAction attribute to the errorHandler component to specify the route where the error occurs

Examples to explain how PHP handles errors and exceptions in the Yii framework

Generally speaking, what we are most concerned about is the display of error pages in production mode. After the above analysis, there are two methods available:

Define the errorAction routing attribute for the errorHandler component in the configuration file (should take precedence Use this method to achieve flexible configuration)

Define any one 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 first method is flexible and controllable. You can specify the view file in the controller, which is flexible and controllable.

Example of using error handler

yii\web\ErrorHandler is registered as an application component named errorHandler, which can be configured in the application configuration as follows:

return [
'components' => [
'errorHandler' => [
'maxSourceLines' => 20,
],
],
];
Copy after login

Use as above Code, the exception page displays up to 20 source codes.

As mentioned before, the error handler converts all non-fatal PHP errors into gettable exceptions, which means you can use the following code to handle PHP errors:

use Yii;
use yii\base\ErrorException;
try {
10/0;
} catch (ErrorException $e) {
Yii::warning("pision by zero.");
}
// execution continues...
Copy after login

If you want to display an error The page tells the user that the request is invalid or cannot be processed by simply throwing a yii\web\HttpException, such as yii\web\NotFoundHttpException. The error handler will correctly set the response HTTP status code and use the appropriate error view page to display the error message.

use yii\web\NotFoundHttpException;
throw new NotFoundHttpException();
Copy after login

Customized error display

yii\web\ErrorHandler The error handler adjusts the error display according to the value of the constant YII_DEBUG. When YII_DEBUG is true (indicating that it is in debug mode), the error handler will Display exceptions and detailed function call stacks and source code lines to help debugging. When YII_DEBUG is false, only error information will be displayed to prevent the leakage of sensitive information of the application.

Supplement: If the exception inherits yii\base\UserException, no matter what the value of YII_DEBUG is, the function call stack information will not be displayed. This is because this kind of error will be considered to be a user-generated error, and developers cannot Needs to be corrected.

yii\web\ErrorHandler The error handler uses two views to display errors by default:

@yii/views/errorHandler/error.php: The error message that does not include function call stack information is displayed. Used when YII_DEBUG is false, this view is used for all errors.

@yii/views/errorHandler/exception.php: Used when displaying error messages containing function call stack information.

You can configure the yii\web\ErrorHandler::errorView and yii\web\ErrorHandler::exceptionView properties of the error handler to use a custom error display view.

Use error action

It is more convenient to use the specified error action to customize the error display. To do this, first configure the yii\web\ErrorHandler::errorAction attribute of the errorHandler component, similar to the following:

return [
'components' => [
'errorHandler' => [
'errorAction' => 'site/error',
],
]
];
Copy after login

yii\web\ErrorHandler::errorAction attribute is used to route to an action. The above configuration indicates that errors that do not need to display function call stack information will be displayed by executing the site/error operation.

The site/error operation 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',
],
];
}
}
Copy after login

The above code defines the error operation using the yii\web\ErrorAction class, which renders a view named error to display errors.

In addition to using yii\web\ErrorAction, the error operation can be defined using an operation method similar to the following:

public function actionError()
{
$exception = Yii::$app->errorHandler->exception;
if ($exception !== null) {
return $this->render('error', ['exception' => $exception]);
}
}
Copy after login

Now a view file should be created as views/site/error.php, in this view In the file, if the error action is defined as yii\web\ErrorAction, you can access the following variables defined in the operation:

name: Error name

message: Error message

exception: Exception object with more detailed information, such as HTTP status code, error code, error call stack, etc.

Supplement: If you use the Basic Application Template or the Advanced Application Template, error operations and error views have already been defined.

Custom error format

The error handler displays errors according to the format set by the response. If the yii\web\Response::format response format is html, the error or exception view will be used to display it. error message, as described in the previous section. For other response formats, the error handler assigns the error information as an array to the yii\web\Response::data attribute, and then converts it 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, 02 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 was not found.",
"code": 0,
"status": 404
}
Copy after login

You can customize the error response format by responding to the beforeSend event of the response component in the application configuration.

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 = 200;
}
},
],
],
];
Copy after login

上述代码会重新格式化错误响应,类似如下:

HTTP/1.1 200 OK
Date: Sun, 02 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
{
"success": false,
"data": {
"name": "Not Found Exception",
"message": "The requested resource was not found.",
"code": 0,
"status": 404
}
}
Copy after login

推荐学习:php视频教程

The above is the detailed content of Examples to explain how PHP handles errors and exceptions in the Yii framework. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template