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 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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles