Home Backend Development PHP7 Examples to explain how PHP handles errors and exceptions in the Yii framework

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

Jul 16, 2021 am 09:11 AM
php

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1667
14
PHP Tutorial
1273
29
C# Tutorial
1255
24
PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles