yii: exception error not rendering view nor layout outside an action

by prettyscripts on 2011-08-10 11:48

phpyii

because there are certain validations need to be done before an action is run, a new controller component is added to do such validations to avoid repeating codes. however, the page is not displayed properly as per error view file if there is exception error.

eg, if done in an action function in controller/DefaultController.php, this renders propertly:

PHP:

class DefaultController extends Controller {
    public function actionIndex() {
        if (!some_validation())
            throw new CHttpException(400'Validation failed.');
        ....
    }
}

to avoid repeating the validation code in every single action functions, a parent controller is created, components/MyController.php.

now, if validation is done in the parent controller, the exception error does not render properly:

PHP:

class MyController extends Controller {
    protected beforeAction($action) {
        if (!parent::beforeAction($action)) return false;
        if (!some_validation())
            throw new CHttpException(400'Validation failed.');
        ....
        return true;
    }
}

i can't seem to find any information on this. i'm not sure if this is intended or a bug. i'm also not sure if this is the correct way to do it. please correct me if i'm wrong.

as a solution, try to catch the error in beforeAction() and render the output from there:

PHP:

protected beforeAction($action) {
    if (!parent::beforeAction($action)) return false;
    try {
        if (!some_validation())
            throw new CHttpException(400'Validation failed.');
    } catch (Exception $e) {
        $this->render('error'array(
           // pass any necessary error data to error view file
           'error' => $e,    
        ));
        return false;
    }
    ....
    return true;
}

the error should now be displayed in accordance to your project layout and error view file.