美文网首页
Yii2整站的统一错误处理控制器设计

Yii2整站的统一错误处理控制器设计

作者: 沪江快速手机打字 | 来源:发表于2017-05-27 18:02 被阅读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 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);
    }
}

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("index",['article'=>$article]);
    }else{
        //在需要显示错误信息的地方直接调用error()方法即可。
        return $this->error('你查找的文章不存在!',[['Home','/']],3);
        echo "error()方法之后的内容将不再显示出来!";
    }
    }
}

(全文完)

相关文章

网友评论

      本文标题:Yii2整站的统一错误处理控制器设计

      本文链接:https://www.haomeiwen.com/subject/bmwqfxtx.html