I have following config of errorHandler
'errorHandler' => [
'errorAction' => 'page/error',
],
In the Controller page, in the Action error I want to check, that I got 404 error "page not found"?
How can I check it?
If you are trying to customize an Error page and want to get the errors code separately inside the view then you have the $exception,$name and $message variables available inside the view, but in case if you use yii\web\ErrorAction, before I go ahead you need to see in which category you fall.
\yii\web\ErrorAction
Inside your PageController you should have an actions() function like below.
public function actions() {
return [
'error' => [
'class' => 'yii\web\ErrorAction' ,
]
];
}
If you haven't created a separate layout for error add one now, it better to keep your error layout separate. Just copy the layouts/main.php and remove all extra CSS and js files or create frontend/assets/ErrorAsset.php and register on top of your layout file.
Add beforeAction() function inside your PageController like below.
Sample Code
public function beforeAction( $action ) {
if ( parent::beforeAction ( $action ) ) {
//change layout for error action after
//checking for the error action name
//so that the layout is set for errors only
if ( $action->id == 'error' ) {
$this->layout = 'error';
}
return true;
}
}
Now as you have specified the 'page/error' inside your errorHandler component's config so the action name would be error and so would be the view file, this view file should be inside the page folder this should be the path page/error.php. You have the $exception variable available which holds the exception object in your case yii\web\NotFoundHttpException Object. and you can call $exception->statusCode to check which status code has been thrown for the exception, in your case, it would show 404.
Another Way is to use custom action inside the controller rather than using the yii\web\ErrorAction in that case you do not need to add the actions() function and inside your custom error function you should call
$exception = Yii::$app->getErrorHandler()->exception;
and use the $exception->statusCode. Make sure you check for the exact action name for inside your beforeAction() function change your check accordingly for the line
if ( $action->id == 'error' ) {
If you don't want any of above and just want to check the Exception code inside the controller's beforeAction() you have to access the same exception object above but with a shorthand via config's erorHandler component.
public function beforeAction($action) {
$exception = Yii::$app->getErrorHandler()->exception;
if(parent::beforeAction($action)) {
$hasError = $action->id == 'error' && $exception !== NULL;
if($hasError) {
echo $exception->statusCode;
return false;
}
}
return true;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With