重寫Handel的render()方法
<?php namespace app\lib\exception; use Exception; use think\exception\Handle; use think\facade\Log; class ExceptionHandle extends Handle { private $code; private $msg; private $errorCode; // 需要返回客戶端當前請求的URL路徑 public function render(\Exception $e) { if ($e instanceof BaseException) { // 如果是自定義的異常 $this->code = $e->code; $this->msg = $e->msg; $this->errorCode = $e->errorCode; Log::close(); //關閉日志寫入 } else { if (config('app.app_debug')) { return parent::render($e); } else { $this->code = 500; $this->msg = '服務器內部錯誤'; $this->errorCode = 999; } } $result = [ 'msg' => $this->msg, 'error_code' => $this->errorCode, 'request_url' => request()->url() ]; return json($result, $this->code); } }
在配置文件中,修改異常處理類地址
默認輸出類型改為 json
基礎異常類
<?php namespace app\lib\exception; use think\Exception; class BaseException extends Exception { // http狀態碼 正常200 public $code = 400; // 錯誤具體信息 public $msg = '參數錯誤'; // 自定義的錯誤碼 public $errorCode = 10000; public function __construct($params = []) { if (!is_array($params)) { // return; throw new Exception('參數必須是數組'); } if(array_key_exists('code',$params)){ $this->code = $params['code']; } if(array_key_exists('msg',$params)){ $this->msg = $params['msg']; } if(array_key_exists('errorCode',$params)){ $this->errorCode = $params['errorCode']; } } }
自定義異常 例如自定義一個輪播圖異常
<?php namespace app\lib\exception; class BannerMissException extends BaseException { public $code = 404; public $msg = '請求的banner不存在'; public $errorCode = 40000; }
如果查詢的輪播圖信息不存在,拋出該異常
<?php namespace app\api\controller\v1; use app\api\validate\IDMustBePositiveInt; use app\lib\exception\BannerMissException; use think\Controller; class Banner extends Controller { /** * 獲取指定id的banner輪播圖信息 * @url /banner/:id * @http GET * @id banner的id號 */ public function getBanner($id) { // 驗證參數id (new IDMustBePositiveInt())->goCheck(); // 查詢banner信息 $banner = model('Banner')->getBannerID($id); if (!$banner) { // 如果查詢不存在 拋出自定義異常信息 throw new BannerMissException(); } return $banner; } }