Search code examples
phpyii2httpexception

Display Yii2 HttpException Message in View


I try to handle HttpExceptions in Yii2 to Display Errormessages for Webusers. I Set everything up like here: http://www.yiiframework.com/doc-2.0/guide-runtime-handling-errors.html

Controller

namespace app\controllers;

use Yii;
use yii\web\Controller;

class SiteController extends Controller
{
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }
}

public function actionError()
{
    $exception = Yii::$app->errorHandler->exception;
    if ($exception !== null) {
        return $this->render('error', ['exception' => $exception]);
    }
}

When i throw an error like this:

throw new HttpException(404,"This is an error. Maybe Page not found!");

I want to Display the Text in my view File or at least the vars described in the Docs - but alle vars are proteced or private. Any ideas how to do this?

View

$exception->statusCode // works
$exception->message    // proteced

Solution

  • Firstly, you're defining the error action twice, once as a method of your siteController, and secondly in the actions method. Your error message can be retrieved using the '$message' variable in your view file, using $exception->message is not correct. The Yii documentation allows for these variables in your error view file;

    • name
    • message
    • exception