Home > PHP Framework > YII > body text

How to handle errors in Yii framework

(*-*)浩
Release: 2020-01-08 15:24:17
Original
2465 people have browsed it

How to handle errors in Yii framework

Yii has a built-in error handler, which makes error handling more convenient. The Yii error handler does the following to improve the error handling effect:

All non-fatal PHP errors (such as warnings, prompts) will be converted into obtainable exceptions;                                                                                                                                 Exceptions and fatal PHP errors will be displayed, and detailed function call stacks and source code lines will be displayed in debug mode.

Supports using dedicated controller operations to display errors; Supports different error response formats;

error handler The error handler is enabled by default and can be passed in Define the constant YII_ENABLE_ERROR_HANDLER in the application's entry script to disable it.

Use error handler

The error handler 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
Using the above code, the exception page will display up to 20 source codes.

As mentioned before, the error handler converts all non-fatal PHP errors into catchable 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("Division by zero.");
}
// execution continues...
Copy after login

If you want to display an error page telling the user that the request is invalid or cannot be handled, simply throw an HTTP exception, 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

The above is the detailed content of How to handle errors in Yii framework. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template