Error handling | basic functions | Yii Chinese document 2.0.x

error handling

Yii has a built-in [[yii\web\ErrorHandler|error handler]] error handler, which makes error handling more convenient. Yii error handler does the following work to improve the effect of error handling:

  • All non fatal PHP errors (such as warnings and prompts) will be converted into fetchable exceptions;
  • Exceptions and fatal PHP errors will be displayed, and the detailed function call stack and source code lines will be displayed in debugging mode.
  • Support the use of dedicated Controller operation To display errors;
  • Support different error response formats;

[[yii\web\ErrorHandler|error handler]] the error handler is enabled by default and can be used in the application Entry script Constant Yii defined in_ ENABLE_ ERROR_ Handler to disable.

Use error handler

[[yii\web\ErrorHandler|error handler]] register as an errorHandler Application component , you can configure it in the application configuration, similar to the following:

return [
    'components' => [
        'errorHandler' => [
            'maxSourceLines' => 20,
        ],
    ],
];

Using the above code, the exception page displays up to 20 source codes.

As mentioned earlier, the error handler converts all non fatal PHP errors into fetchable exceptions, that is, PHP errors can be handled using the following code:

use Yii;
use yii\base\ErrorException;

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

// execution continues...

If you want to display an error page to tell the user that the request is invalid or cannot be processed, you can simply throw an [[yii\web\HttpException|HTTP exception]] exception, such as [[yii\web\NotFoundHttpException]]. The error handler will correctly set the HTTP status code of the response and use the appropriate error view page to display the error message.

use yii\web\NotFoundHttpException;

throw new NotFoundHttpException();

Custom error display

[[yii\web\ErrorHandler|error handler]] error handler according to constant YII_DEBUG value to adjust the error display when YII_DEBUG is true (indicating that it is in debugging mode), and the error handler will display exceptions, as well as detailed function call stack and source code lines to help debugging. When YII_DEBUG is false, and only error information will be displayed to prevent the leakage of sensitive information of the application.

Info: if the exception is inherited [[yii\base\UserException]], regardless of Yii_ The value of debug and the function call stack information will not be displayed, because this error will be considered as a user generated error and developers do not need to correct it.

[[yii\web\ErrorHandler|error handler]] two error handlers are used by default view Display error:

  • @yii/views/errorHandler/error.php: the error message that does not contain function call stack information is used when Yii_ When debug is false, all errors use this view.
  • @yii/views/errorHandler/exception.php: used when displaying error messages containing function call stack information.

You can configure the [[yii\web\ErrorHandler::errorView|errorView]] and [[yii\web\ErrorHandler::exceptionView|exceptionView]] properties of the error processor to use a custom error display view.

Use wrong action

Use specified error operation It is more convenient to customize the error display. For this purpose, first configure the [[yii\web\ErrorHandler::errorAction|errorAction]] attribute of the errorHandler component, similar to the following:

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

[[yii\web\ErrorHandler::errorAction|errorAction]] property use route To an operation, the above configuration indicates that the error without displaying the function call stack information will be displayed by executing the site/error operation.

You can create site/error actions as follows:

namespace app\controllers;

use Yii;
use yii\web\Controller;

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

The above code defines the error operation and uses the [[yii\web\ErrorAction]] class, which renders the view named error to display errors.

In addition to using [[yii\web\ErrorAction]], you can define the error action, and use the following operation methods:

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

Now you should create a view file called views / site / error PHP. In the view file, if the error action is defined as [[yii\web\ErrorAction]], you can access the following variables defined in the action:

  • Name: error name
  • Message: error message
  • Exception: exception object with more detailed information, such as HTTP status code, error code, error call stack, etc.

Note: if you use Basic application template or Advanced application template , error actions and error views have been defined.

Note: if you need to redirect in the error handler, do the following:

Yii::$app->getResponse()->redirect($url)->send();
return;

Custom error format

Error processor based on response Set the format to display the error. If the [[yii\web\Response::format|response format]] response format is html, the error or exception view will be used to display the error information, as described in the previous section. For other response formats, the error processor 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
}

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;
                }
            },
        ],
    ],
];

The above code will reformat the error response, similar to the following:

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

💖 Those who like this document are welcome to like, collect, leave a message or forward it. Thank you for your support! Author email: zhuzixian520@126.com

This article was first published in LearnKu.com On the website.

Added by sujata_ghosh on Sun, 06 Feb 2022 07:47:46 +0200