如果不進過異常封裝,如果拋出一異常只會只會上圖所示,大部分時候,用戶只需要知道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如圖所示。