阿江 2017-01-10 10:32:52 7248次浏览 3条回复 13 4 0

一、需求描述:

在Yii2开发中会有各种各样的错误出现,除了YII_DEBUG为真状态时的调试页面而外(Debugger喜欢的再没谁了!),更需要一个对终端用户统一显示的,更加友好的错误提示页面。

二、解决思路:

定义一个CommonController统一处理整站的错误提示信息,创建新的Controller时继承自CommonController就可以了,在需要显示错误信息的地方调用CommonController的公共方法即可,样式设计上则参照了Ecshop的跳转链接列表样式。在CommonController中除了错误信息(error)提示之外,还有普通信息(info)的显示处理,操作成功(success)的提示。话不多说,上代码:

三、源代码:

1、定义CommonController

文件位置:D:\phpwork\advanced\frontend\controllers\CommonController.php

<?php
namespace frontend\controllers;
use yii\web\Controller;
class CommonController extends Controller{
   /*
     * 操作成功显示提示信息
     * @param string $info,显示的信息提示
     * @param array $url,二维数组,将要跳转的链接,格式:[[urlText1,url1],[urlText2,url2]......]
     * @param int $jumpseconds,自动跳转到第一个链接的秒数,-1:不自动跳转;0:当即跳转;大于0的整数:信息显示的秒数
     * @return
    * sample:
    * $this->success('Submit success,Thank you!',[['首页','/'],['购物车','/shopping-cart/index']],3);
     * */
    public function success($info,$url=[],$jumpSeconds=-1){
        if(!empty($url)&&empty($jumpSeconds)){
            return $this->redirect($url[0]);
        }else{
            $this->layout='main';
            echo $this->render('@frontend/views/success',[
                'info'=>$info,
                'url'=>$url,
                'jumpSeconds'=>$jumpSeconds,
            ]);
        }
        exit;
    }
    /*
     * 操作失败显示提示信息
     * @param string $info,显示的信息提示
     * @param array $url,二维数组,将要跳转的链接,格式:[[urlText1,url1],[urlText2,url2]......]
     * @param int $jumpseconds,自动跳转到第一个链接的秒数,-1:不自动跳转;0:当即跳转;大于0的整数:信息显示的秒数
     * @return
     * */
    public function error($info,$url=[],$jumpSeconds=-1){
        if(!empty($url)&&empty($jumpSeconds)){
            return $this->redirect($url[0]);
        }else{
            echo $this->render('@frontend/views/errormsg',[
                'info'=>$info,
                'url'=>$url,
                'jumpSeconds'=>$jumpSeconds,
            ]);
        }
        exit;
    }
    /*
     * 调用信息提示页面
     * @param string $info,显示的信息提示
     * @param array $url,二维数组,将要跳转的链接,格式:[[urlText1,url1],[urlText2,url2]......]
     * @param int $jumpseconds,自动跳转到第一个链接的秒数,-1:不自动跳转;0:当即跳转;大于0的整数:信息显示的秒数
     * @return
     * */
    public function info($info,$url=[],$jumpSeconds=-1){
        if(!empty($url)&&empty($jumpSeconds)){
            return $this->redirect($url[0]);
        }else{
            echo $this->render('@frontend/views/info',[
                'info'=>$info,
                'url'=>$url,
                'jumpSeconds'=>$jumpSeconds,
            ]);
        }
        exit;
    }
}
2、定义错误视图文件errormsg.php,还有两个视图文件:success.php和view.php与此类似,可参照自行修改。

文件位置:D:\phpwork\advanced\frontend\views\errormsg.php

<?php

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

use yii\helpers\Html;
$this->title ="MyWeb";
?>
<div class="container">
    <div class="hint-main hint-error">
        <h1></h1>
        <h2>ERROR INFORMATION</h2>
        <h3><?= nl2br(Html::encode($info)) ?></h3>
        <?php
        $str='';
        if(!empty($url)){
            $str.='<h4>You can select:';
            foreach($url as $item){
                $str.="<a href='".$item[1]."'>".$item[0]."</a>";
            }
            if($jumpSeconds>=0){
                $str.="<BR><BR>".Yii::t('app','After ').$jumpSeconds.Yii::t('app',' seconds').Yii::t('app',' will jump to')." '<a href='".$url[0][1]."'>".$url[0][0]."</a>'<meta http-equiv=refresh content=".$jumpSeconds.";url=".$url[0][1].">";
            }
            $str.='</h4>';
        }
        echo $str;
        ?>
    </div>
</div>

3、使用CommonController中公共方法error()进行错误提示

文件位置:D:\phpwork\advanced\frontend\controllers\SiteController.php

namespace frontend\controllers;
class SiteController extends CommonController{
    public function actionDetail($id){
	$query = new \yii\mongodb\Query;
	$article = $query->select(['title', 'content'])
		->from('article')
		->where(['_id' => $id])
		->limit(1)
		->one();
	if($article){
		$this->render("detail",['article'=>$article]);
	}else{
		//在需要显示错误信息的地方直接调用error()方法即可。
		$this->error('你查找的文章不存在!',[['Home','/']],3);
		echo "error()方法之后的内容将不再显示出来!";
	}
    }
}

(全文完)

觉得很赞
  • 回复于 2017-03-21 18:09 举报

    改进:
    //2017-3-11更新,增加errorDisplay($errorArray),用于显示表单服务器验证出错时的信息显示
    //2017-3-21更新,将原有的exit;方法去掉,使用return返回渲染模板,这样不会更改Yii的完整生命周期。注意:调用时也需要使用return!

    文件位置:D:\phpwork\advanced\frontend\controllers\CommonController.php

    namespace frontend\controllers;
    use yii\web\Controller;
    class CommonController extends Controller{
       /*
         * 操作成功显示提示信息
         * @param string $info,显示的信息提示
         * @param array $url,二维数组,将要跳转的链接,格式:[[urlText1,url1],[urlText2,url2]......]
         * @param int $jumpseconds,自动跳转到第一个链接的秒数,-1:不自动跳转;0:当即跳转;大于0的整数:信息显示的秒数
         * @return exit
        * sample:
        * return $this->success('Submit success,Thank you!',[['首页','/'],['购物车','/shopping-cart/index']],3);
         * */
        public function success($info,$url=[],$jumpSeconds=-1){
            if(!empty($url)&&empty($jumpSeconds)){
                return $this->redirect($url[0]);
            }else{
                $this->layout='empty';
                return $this->render('@app/views/success',[
                    'info'=>$info,
                    'url'=>$url,
                    'jumpSeconds'=>$jumpSeconds,
                ]);
            }
        }
        /*
         * 操作失败显示提示信息
         * @param string $info,显示的信息提示
         * @param array $url,二维数组,将要跳转的链接,格式:[[urlText1,url1],[urlText2,url2]......]
         * @param int $jumpseconds,自动跳转到第一个链接的秒数,-1:不自动跳转;0:当即跳转;大于0的整数:信息显示的秒数
         * @return exit
         * */
        public function error($info,$url=[],$jumpSeconds=-1){
            if(!empty($url)&&empty($jumpSeconds)){
                return $this->redirect($url[0]);
            }else{
                $this->layout='empty';
                return $this->render('@app/views/errormsg',[
                    'info'=>$info,
                    'url'=>$url,
                    'jumpSeconds'=>$jumpSeconds,
                ]);
            }
        }
        /*
         * 调用信息提示页面
         * @param string $info,显示的信息提示
         * @param array $url,二维数组,将要跳转的链接,格式:[[urlText1,url1],[urlText2,url2]......]
         * @param int $jumpseconds,自动跳转到第一个链接的秒数,-1:不自动跳转;0:当即跳转;大于0的整数:信息显示的秒数
         * @return exit
         * */
        public function info($info,$url=[],$jumpSeconds=-1){
            if(!empty($url)&&empty($jumpSeconds)){
                return $this->redirect($url[0]);
            }else{
                $this->layout='empty';
                return $this->render('@app/views/info',[
                    'info'=>$info,
                    'url'=>$url,
                    'jumpSeconds'=>$jumpSeconds,
                ]);
            }
        }
        /*
         * 显示model数据验证失败错误信息(专用)注意:仅在调试模式时显示
         * 示例: $this->errorDisplay($model->getErrors());
         * @param array $errorArray,错误信息数组,样例:$errorArr=[['Author is empty!']];
         * @return exit
         * */
        public function errorDisplay($errorArray){
            $errorstr="";
            if(YII_DEBUG&&$errorArray&&is_array($errorArray)){
                foreach ($errorArray as $k=>$error) {
                    if(is_array($error)){
                        $errorstr.=implode("\n\n",$error)."\n\n";
                    }else{
                        $errorstr.="Have Error\n\n";
                    }
                }
            }
            if(!$errorstr){
                $errorstr="Have error!\n\n";
            }
            return $this->error($errorstr);
        }
    }
    
  • 回复于 2017-03-21 18:14 举报

    感谢 的改进建议!

  • 回复于 2017-04-26 14:35 举报

您需要登录后才可以回复。登录 | 立即注册