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

一、需求描述:

在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()方法之后的内容将不再显示出来!";
    }
    }
}

(全文完)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • error code(错误代码)=2000是无效的像素格式。error code(错误代码)=2001是指定的驱动...
    Heikki_阅读 6,046评论 0 4
  • error code(错误代码)=0是操作成功完成。error code(错误代码)=1是功能错误。error c...
    Heikki_阅读 8,721评论 1 9
  • 工厂模式类似于现实生活中的工厂可以产生大量相似的商品,去做同样的事情,实现同样的效果;这时候需要使用工厂模式。简单...
    舟渔行舟阅读 12,378评论 2 17
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,380评论 19 139
  • 错误:1000 SQLSTATE: HY000 (ER_HASHCHK)消息:hashchk 错误:1001 SQ...
    灼灼2015阅读 23,786评论 0 6