Yii includes a built-in error handler which makes error handling a much more pleasant experience than before. In particular, the Yii error handler does the following to improve error handling :
* All non-fatal PHP errors (e.g. warnings, notices) are converted into catchable exceptions.
* Exceptions and fatal PHP errors are displayed with detailed call stack information and source code lines in debug mode.
* Supports using a dedicated controller action to display errors.
* Supports different error response formats.
The error handler is enabled by default. You may disable it by defining the constant YII_ENABLE_ERROR_HANDLER
to be false in the entry script of your application.
Using Error Handler : The error handler is registered as an application component named errorHandler
. You may configure it in the application configuration like the following :
return [
'components' => [
'errorHandler' => [
'maxSourceLines' => 20,
],
],
];
With the above configuration, the number of source code lines to be displayed in exception pages will be up to 20.
As aforementioned, the error handler turns all non-fatal PHP errors into catchable exceptions. This means you can use the following code to deal with PHP errors :
use Yii;
use yii\base\ErrorException;
try {
10/0;
} catch (ErrorException $e) {
Yii::warning("Division by zero.");
}
// execution continues...
If you want to show an error page telling the user that his request is invalid or unexpected, you may simply throw an HTTP exception, such as yii\web\NotFoundHttpException
. The error handler will correctly set the HTTP status code of the response and use an appropriate error view to display the error message.
use yii\web\NotFoundHttpException;
throw new NotFoundHttpException();