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 handlerThe 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,
],
],
];
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 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();
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!