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?
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 useyii\web\ErrorAction
, before I go ahead you need to see in which category you fall.CASE 1 Using
\yii\web\ErrorAction
Inside your
PageController
you should have anactions()
function like below.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 createfrontend/assets/ErrorAsset.php
and register on top of your layout file.Add
beforeAction()
function inside yourPageController
like below.Sample Code
Now as you have specified the
'page/error'
inside yourerrorHandler
component's config so the action name would beerror
and so would be the view file, this view file should be inside thepage
folder this should be the pathpage/error.php
. You have the$exception
variable available which holds the exception object in your caseyii\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 show404
.CASE 2 Using Custom Action for displaying Errors
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 theactions()
function and inside your custom error function you should calland use the
$exception->statusCode
. Make sure you check for the exact action name for inside yourbeforeAction()
function change your check accordingly for the lineCASE 3 SHUTUP just Give me the Exception`
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 sameexception
object above but with a shorthand via config'serorHandler
component.