Display Yii2 HttpException Message in View

4k views Asked by At

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
5

There are 5 answers

1
Joe Miller On BEST ANSWER

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
0
Ripper On

Not sure if you checked view file in views\site\error.php took me while to realize myself this is used to display error pages.

<?php

/* @var $this yii\web\View */
/* @var $name string */
/* @var $message string */
/* @var $exception Exception */

use yii\helpers\Html;

$this->title = $name;
?>
<div class="site-error">

    <h1><?= Html::encode($this->title) ?></h1>

    <div class="alert alert-danger">
        <?php /* this is message you set in `HttpException` */ ?>
        <?= nl2br(Html::encode($message)) ?>
    </div>

    <p>
        <?= Yii::t('app', 'Here is text that is displayed on all error pages') ?>
    </p>

</div>
0
Yasar Arafath On

Try this one

  $connection = \Yii::$app->db;
  $transaction = $connection->beginTransaction();

  try {
          $model->save()
          $transaction->commit();
          return $this->redirect(['user/view', 'id' => $model->id]);

      }catch (\Exception $e) {

          $transaction->rollBack();
          throw new \yii\web\HttpException(500,"YOUR MESSAGE", 405);


    }
0
Ras On

Maybe you can try add extra content and extend the exception in Yii2 error message like this. Just create a new custom php file called ErrorMsg.php

<?php
use Yii;
use yii\web\HttpException;
class ErrorMsg extends \Exception
{
    
    public static function customErrorMsg($error_code,$message = null, $code = 0, \Exception $previous = null,$extra_content=NULL)
    {
        $httpException = new HttpException($error_code,$message,$code,$previous);
        Yii::$app->response->statusCode = $error_code;
        $custom_err = array(
                            'name'=> $httpException->getName(),
                            'message' => $message,
                            'code' => $code,
                            'extraContent' => $content,
                            'status' => $error_code,
                            'type' => "\\utilities\\ErrorMsg"
        );
        return $custom_err;
    }

and call the functions wherever you want. Example

return ErrorMsg::customErrorMsg(400,"Message Here",11,NULL,"Extra Content Here");
0
Хасан Шадияров On

If you want to get exception message directly from the exception class (Any of it, e.g. NotFoundException), you find that Exception::$message is protected property, but it has Exception::getMessage() public method, so in your error view, just call it.

<p class="message"><?= $exception->getMessage() ?></p>