2016-12-28 8 views
0

私はWebユーザーのためにErrormessagesを表示するためにYii2でHttpExceptionsを処理しようとします。私はここのようにすべてを設定します。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!"); 

を、私は私のビューファイルまたは少なくともテキストを表示したいですDocsに記述されているvars - しかし、varsは保護されているかプライベートです。どのようにこれを行うにはどのようなアイデア?

ビュー

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

答えて

2

は、まず、あなたが一度あなたのsiteControllerの方法として、二回errorアクションを定義し、そして第二に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

この1

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


    } 
関連する問題