Home  >  Article  >  Backend Development  >  Handling Errors and Exceptions in the Yii Framework: A Comprehensive Guide

Handling Errors and Exceptions in the Yii Framework: A Comprehensive Guide

王林
王林Original
2023-09-02 15:17:01725browse

处理 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