2016-12-28 91 views
0

我尝试处理Yii2中的HttpExceptions以显示Webusers的错误消息。我把一切都弄好喜欢这里:http://www.yiiframework.com/doc-2.0/guide-runtime-handling-errors.html在视图中显示Yii2 HttpException消息

控制器

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]); 
    } 
} 

当我把这样的错误:

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

我想显示的文字在我看来,文件或至少文档中描述的变量 - 但变量变量被保护或私有。任何想法如何做到这一点?

查看

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

回答

2

首先,你定义的error行动两次,一次为您siteController的方法,其次在actions方法。 您的错误消息可以使用视图文件中的'$ message'变量检索,使用$exception->message不正确。 Yii文档允许在错误视图文件中使用这些变量;

  • 消息
  • 例外
+0

谢谢,我知道了。像你描述的那样工作。但是如何显示我在HttpException中设置的消息文本? – kasoft

1

不知道,如果你选中视图文件中views\site\error.php带我一段时间才能意识到自己这是用来显示错误页面。

<?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

谢谢,最后我得到了它的工作 – kasoft

0

试试这个

$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); 


    }