search
HomeBackend DevelopmentPHP TutorialHandling Errors and Exceptions in the Yii Framework: A Comprehensive Guide

处理 Yii 框架中的错误和异常:综合指南

Introduction

In today's tutorial, I'll introduce Yii's error and exception handling and guide you through some introductory scenarios.

Want to know what Yii is? Check out our Introduction to the Yii Framework and Yii2 Programming series.

What is the difference between errors and exceptions?

Bugs are unexpected flaws in our code, often discovered first by users. They usually interrupt program execution. It's important not only to break gracefully for the user, but also to notify the developer of the problem so it can be fixed.

Developers create exceptions when potentially predictable error conditions occur. In code where exceptions may occur, developers can throw() exceptions to robust error handlers.

How does Yii manage these?

In Yii, non-fatal PHP errors (such as warnings and notifications) are routed into catchable exceptions so that you can decide how to react and respond to them. You can specify a controller action to handle all these exceptions. You can also customize the error display format, such as HTML, JSON, XML, etc.

Exceptions and fatal PHP errors can only be evaluated in debug mode. In these types of development scenarios, Yii can display detailed call stack information and source code snippets (you can see this in the header image above).

A fatal error is a type of event that interrupts application execution. These include out of memory, instantiating an object of a non-existent class, or calling a non-existent function.

For example:

$t = new Unknownobject();

Let's start by looking at some examples of error and exception handling.

Configuration error and exception handling

First, we configure our application in frontend/config/main.php. errorHandler is defined as a component as shown below. This example is from my startup series application, Meeting Planner. Please note the configuration of errorHandler in components:

<?php
$params = array_merge(
    require(__DIR__ . '/params.php'),
    require(__DIR__ . '/params-local.php')
);
return [
    'id' => 'mp-frontend',
    'name' => 'Meeting Planner',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log','\common\components\SiteHelper'],
    'controllerNamespace' => 'frontend\controllers',
    'catchAll'=> [],
    'components' => [
      'assetManager' => [...],
      ...
      'errorHandler' => [
            'errorAction' => 'site/error',
            'maxSourceLines' => 20,
        ],
        ...
    ],
];

In the example above, errorAction directs the user to the error action of my SiteController.

More broadly, Yii provides a variety of configuration options for errorHandler for redirection and data collection:

Attributes type describe
$callStackItemView String Path to the view file used to render exception and error call stack elements. For example '@yii/views/errorHandler/callStackItem.php'
$displayVars Array List of PHP predefined variables that should be displayed on error pages. For example ['_GET', '_POST', '_FILES', '_COOKIE', '_SESSION']
$errorAction String Route for controller actions that display external errors (e.g. site/error).
$errorView String Path to the view file used to render exceptions without call stack information. For example '@yii/views/errorHandler/error.php'
$Exception view String The path to the view file that renders the exception. For example '@yii/views/errorHandler/exception.php'
$maxSourceLines Integer Maximum number of source code lines to display.
$maxTraceSourceLines Integer Maximum number of trace source code lines to display.
$previousExceptionView String Path to the view file used to render the previous exception. For example '@yii/views/errorHandler/previousException.php'

使用 errorActions 直接执行

通常,当用户遇到严重错误时,我们希望将他们重定向到友好的、描述性的错误页面。

这就是 errorHandler 中的 errorAction 的作用。它重定向到我们的 SiteController 的 actionError:

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

在我们的 SiteController 中,我们定义了一个显式的 error 操作:

namespace app\controllers;

use Yii;
use yii\web\Controller;

class SiteController extends Controller
{
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }
}

这是一个基本的错误处理程序(您可以在此处阅读有关这些内容的更多信息):

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

无论是否存在错误或页面请求是否在您的应用程序中不存在,您也可以做出不同的响应:

public function actionError()
    {
        $exception = Yii::$app->errorHandler->exception;
        if ($exception instanceof \yii\web\NotFoundHttpException) {
            // all non existing controllers+actions will end up here
            return $this->render('pnf'); // page not found
        } else {
          return $this->render('error', ['exception' => $exception]);
        }
    }

这是我当前的 Page Not Found 404 错误处理程序:

处理 Yii 框架中的错误和异常:综合指南

理论上,您可以包含链接的站点地图、与页面请求类似的建议页面、搜索功能和联系支持错误页面上的链接。所有这些都可以帮助用户恢复并优雅地继续前进。

这是我当前的一般错误页面(显然我需要添加功能)

处理 Yii 框架中的错误和异常:综合指南

捕获异常

如果我们想要监视一段代码是否存在问题,我们可以使用 PHP try catch 块。下面,我们将通过触发致命除以零错误进行实验:

use Yii;
use yii\base\ErrorException;

...

    try {
        10/0;
    } catch (ErrorException $e) {
        Yii::warning("Division by zero.");
    }
    
...

上面的 catch 响应是为日志生成警告。 Yii 有广泛的日志记录:

  • Yii::trace():记录一条消息以跟踪一段代码的运行情况。主要用于开发。
  • Yii::info():记录一条消息,传达有关事件的信息。
  • Yii::warning():记录发生意外事件的警告消息
  • Yii::error():记录一个致命错误以供调查

如果您希望将用户定向到我们之前配置的错误页面,而不是记录事件,则可以通过事件抛出异常:

use yii\web\NotFoundHttpException;

throw new NotFoundHttpException();

下面是我们抛出带有特定 HTTP 状态代码和自定义消息的异常的示例:

  try {
          10/0;
      } catch (ErrorException $e) {
        throw new \yii\web\HttpException(451,
            'Tom McFarlin\'s humor is often lost on me
                (and lots of people).');
    }

对于用户来说,该代码如下所示:

处理 Yii 框架中的错误和异常:综合指南

关于 Yii 日志记录

Yii 中的所有错误都会根据您的设置方式进行记录。您可能还对我有关用于登录 Yii 的 Sentry 和 Rollbar 的教程感兴趣:

  • 处理 Yii 框架中的错误和异常:综合指南

    构建您的初创公司:错误日志

    处理 Yii 框架中的错误和异常:综合指南

Yii

结束时

我希望您喜欢我们对错误和异常处理的探索。请关注我们的“使用 Yii2 编程”系列中即将推出的教程,我们将继续深入探讨该框架的不同方面。

如果您想更深入地了解 Yii 应用程序开发,请查看我们的使用 PHP 构建您的初创公司系列,该系列使用 Yii2 的高级模板。它讲述了对 Meeting Planner 的每个步骤进行编程的故事。如果您想从头开始学习如何在 Yii 中构建应用程序,它会非常有用。

如果您想知道下一个 Yii2 教程何时发布,请在 Twitter 上关注我@lookahead_io 或查看我的讲师页面。

相关链接

  • yii\web\ErrorHandler 文档
  • 处理错误(Yii 2.0 权威指南)
  • 日志记录(Yii 2.0 权威指南)
  • Yii2 Developer Exchange(作者的资源网站)

The above is the detailed content of Handling Errors and Exceptions in the Yii Framework: A Comprehensive Guide. 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
PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 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 and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor