TP5:异常处理封装——3

如果不进过异常封装,如果抛出一异常只会只会上图所示,大部分时候,用户只需要知道Division by zero就够了。

1、首先先建一个类BaseException并继承Exception,这里有三个参数 $code =400; $msg ;  $errorCode ;并处理当抛出异常时的参数。

下面要用来一个面向截面的思想,我们打开config.php这个文件,找到exception_handle这一项,会发现“异常处理handle类 留空使用 \think\exception\Handle”这个字样,事实上,当我们不做处理时,抛出异常是会经过\think\exception\Handle处理,而现在我们要自己建处理Handle类。

   

代码如下,新建一个ExceptionHandler类并继承Handle基类,开始还是创建三个变量$code;$msg;$errorCode;并重写render方法,注:这里要使用use think\Exception,不然会出现HttpException这种异常会不能处理的情况,

class ExceptionHandler extends Handle
{
    private $code;
    private $msg;
    private $errorCode;
public function render(Exception $e)
{
   if($e instanceof BaseException){                 //是否为BaseException继承类
       $this->code =$e ->code;
       $this->msg =$e ->msg;
       $this->errorCode =$e ->errorCode;
   }else{
       if(config("app_debug")==true){              //如是开启调试,就走原来的方法
           return parent::render($e);
       }else{                                      //如是关闭调试,是未知错误,我们只需要统一回复
           $this->code = 500;
           $this->msg = 'sorry,we make a mistake. (^o^)Y';
           $this->errorCode = 999;
           $this->recodeErrorLog($e);                      //记录到日志中,这个下一节会讲
       }

   }
    $request = Request::instance();                      //参数实例
    $result=[
        "msg"=> $this->msg,
        "errorCode" =>$this->errorCode,
        "require_url"=>$request->url()                   //取出访问时的URL
    ];
    return json($result,$this->code);
}

做完上一步就可以说封装好了,当我们需要抛了特定的异常时,我们只需要在建一个类,如图MissException并继承BaseException如图所示。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章