search
HomePHP FrameworkYIIyii2 custom error handling

yii2 custom error handling

Dec 14, 2019 am 09:34 AM
yii2

yii2 custom error handling

When using Yii2, we found that once an error occurs in the program, Yii2 can automatically display its dedicated error prompt interface, which is completely different from the error prompt interface that appeared when we wrote the original ecology. Same.

How is it done: Where is the monitoring set up? Or where to use try catch? ”.                                                                       (Recommended learning: yii framework)

In fact, PHP has its own dedicated error handling API. When a problem occurs in the program, the specified function can be automatically called. And Yii2 takes advantage of this. , when it starts, use PHP's built-in set_error_handler to register its own error handling and turn off PHP's own error display.

Yii2 Error custom processing

In the official tutorial, it tells us that to enable custom errors, we need to configure the components as follows:

return [
    // ...
    
    'components' => [
        // ...
        
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],
    ]
    
    // ...
];

Yii2 Error core processing method

In Yii2 In error customization processing, we understand the principle of Yii2 error registration and know that after the error occurs, Yii2 will call the handleException and handleError methods of the yii\web\ErrorHandler class object.

In fact, yii\web\ There are no handleException and handleError methods in the ErrorHandler class, but there are in its base class yii\base\ErrorHandler. These two functions will eventually call the renderException method of yii\web\ErrorHandler. The code is as follows:

# yii\web\ErrorHandler
/**
 * Renders the exception.
 * @param \Exception $exception the exception to be rendered.
 */
protected function renderException($exception)
{
    // ...
    // 注意:控制错误是否能自定义的关键
    // !YII_DEBUG 表示了如果你现在是在 Debug 模式下,那么不能自定义错误
    // 即使你配置了组件的 'errorHandler' => ['errorAction' => 'site/error'] 参数
    $useErrorView = $response->format === Response::FORMAT_HTML && (!YII_DEBUG || $exception instanceof UserException);
    // 传递到自定义错误处理方法
    if ($useErrorView && $this->errorAction !== null) {
        $result = Yii::$app->runAction($this->errorAction);
        if ($result instanceof Response) {
            $response = $result;
        } else {
            $response->data = $result;
        }
    }
    
    // ...
}

In The final error display method renderException we can see: customized errors need to be in non-DEBUG mode to take effect

The above is the detailed content of yii2 custom error handling. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Yii Developers: Common ErrorsYii Developers: Common ErrorsMay 12, 2025 am 12:04 AM

ThemostcommonerrorsinYiiframeworkare"UnknownProperty","InvalidConfiguration","ClassNotFound",and"ValidationErrors".1."UnknownProperty"errorsoccurwhenaccessingnon-existentproperties;ensurepropertiesexi

Yii Developer: Most recquired skills in EuropeYii Developer: Most recquired skills in EuropeMay 11, 2025 am 12:02 AM

The key skills that European Yii developers need to possess include: 1. Yii framework proficiency, 2. PHP proficiency, 3. Database management, 4. Front-end skills, 5. RESTful API development, 6. Version control system, 7. Testing and debugging, 8. Security knowledge, 9. Agile methodology, 10. Soft skills, 11. Localization and internationalization, 12. Continuous learning, these skills make developers stand out in the European market.

Yii: Is the community still active?Yii: Is the community still active?May 10, 2025 am 12:03 AM

Yes,theYiicommunityisstillactiveandvibrant.1)TheofficialYiiforumremainsaresourcefordiscussionsandsupport.2)TheGitHubrepositoryshowsregularcommitsandpullrequests,indicatingongoingdevelopment.3)StackOverflowcontinuestohostYii-relatedquestionsandhigh-qu

Is it easy to migrate a Laravel Project to Yii?Is it easy to migrate a Laravel Project to Yii?May 09, 2025 am 12:01 AM

Migratingalaravel Projecttoyiiishallingbutachieffable WITHIEFLEFLANT.1) Mapoutlaravel component likeroutes, Controllers, Andmodels.2) Translatelaravel's SartisancommandeloequentTooyii's giiandetiverecordeba

Essential Soft Skills for Yii Developers: Communication and CollaborationEssential Soft Skills for Yii Developers: Communication and CollaborationMay 08, 2025 am 12:11 AM

Soft skills are crucial to Yii developers because they facilitate team communication and collaboration. 1) Effective communication ensures that the project is progressing smoothly, such as through clear API documentation and regular meetings. 2) Collaborate to enhance team interaction through Yii's tools such as Gii to improve development efficiency.

Laravel MVC : What are the best benefits?Laravel MVC : What are the best benefits?May 07, 2025 pm 03:53 PM

Laravel'sMVCarchitectureoffersenhancedcodeorganization,improvedmaintainability,andarobustseparationofconcerns.1)Itkeepscodeorganized,makingnavigationandteamworkeasier.2)Itcompartmentalizestheapplication,simplifyingtroubleshootingandmaintenance.3)Itse

Yii: Is It Still Relevant in Modern Web Development?Yii: Is It Still Relevant in Modern Web Development?May 01, 2025 am 12:27 AM

Yiiremainsrelevantinmodernwebdevelopmentforprojectsneedingspeedandflexibility.1)Itoffershighperformance,idealforapplicationswherespeediscritical.2)Itsflexibilityallowsfortailoredapplicationstructures.However,ithasasmallercommunityandsteeperlearningcu

The Longevity of Yii: Reasons for Its EnduranceThe Longevity of Yii: Reasons for Its EnduranceApr 30, 2025 am 12:22 AM

Yii frameworks remain strong in many PHP frameworks because of their efficient, simplicity and scalable design concepts. 1) Yii improves development efficiency through "conventional optimization over configuration"; 2) Component-based architecture and powerful ORM system Gii enhances flexibility and development speed; 3) Performance optimization and continuous updates and iterations ensure its sustained competitiveness.

See all articles

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

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

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools