throwing exception not working from Controller.php

I tried to throw an exception from the Controller.php like this:

throw new CHttpException(404,‘message’);

but instead of rendering the error view it appears a ugly blank page with the error message.

therefore, throwing exceptions seems not to work well in Controller.php, but it works well in a subcontroller. why?

Have you setted ‘errorHandler’ attribute in config?

https://github.com/yiisoft/yii2/blob/master/apps/basic/config/web.php

yes. I said that the exceptions work well in the subcontroller but not in the Controller.php

It seems that layout page is not loaded, but only view is rendered.

Try to check Controller.php if in some place you set $layout globally.

In addition, i’ll try to make (if you haven’t done) a new action with only throw exception. So you can check that the problem is in that specific action and not in all Controller.php.

my first guess is you doing it in the init method if that so then thats where the problem is if that is not the case paste your code here

yes, I’m doing it in the init method.




public function init()

{

	if($condition)

	        throw new CHttpException(404,'message');	

}

what should I do then to throw an exception in the init method of Controller.php?

Try to move throw exception in an action, instead init method.

For example:




public function actionTest()

{

     throw new CHttpException(404,'message'); 

}



I can’t move the exception to an action, since I want to check the language variable for any request to be just ‘en’ or ‘es’




public function init()

{

   if(!isset($_GET['lang'] || ($_GET['lang'] != 'es' && $_GET['lang'] != 'en'))

     throw new CHttpException(404,'Not found'); 

}



You could override beforeAction method to check language.

did you look at this?

http://www.yiiframework.com/doc/api/1.1/CController#beforeAction-detail

I’ve written this code on Controller.php


	protected function beforeAction()

	{

		throw new CHttpException(404,'message');	

	}

but it still appears the ugly screen. Look at the attachment.

The problem is, that you execute the exception twice, because your actionError seems to be a method of the same controller where you throw the exception on beforeAction.

So on handling/rendering the error action the exception will be thrown a second time.

In beforeAction you have to

  • add param action (compatible with the parent)

  • exclude the error action from the exception

  • return true to handle the action




 protected function beforeAction($action)

    {

       if($action->id != 'error')

        throw new CHttpException(404,'message');


       return true;

    }




Another solution is to create an extra error-controller with the actionError, not throwing an exception in beforeAction() or init().

This is the reason why your code is working in a subcontroller correctly, because the actionError is not a method of this controller.

It worked. Thanks!