自定義異常類(restful api)

ThinkPHP框架中的異常類不適合做爲接口開發的異常顯示,一般都須要自定義一個符合項目的異常類。restful api數據結構格式通常是:php

  • status 業務狀態碼
  • message 提示信息
  • data 數據信息

  1. 在項目中新建文件:application\common\lib\exception\ApiHandleException.php,繼承Handle類,覆蓋掉原來的render方法異常處理類。實例代碼:json

    <?php
    
    namespace app\common\lib\exception;
    use think\exception\Handle;
    
    class ApiHandleException extends Handle{
        public $httpCode = 500;
        public function render(\Exception $e){
            if(config('app_debug') == true){
                return parent::render($e);
            }
            if($e instanceof ApiException){
                $this->httpCode = $e->httpCode;
            }
            $data=[
                'status' => 0,
                'message' => $e->getMessage()  ,
                'data' => [],
            ];
            return json($data, $this->httpCode);
        }
    
    }
  2. 在config.php中加入本身定義的異常類的namespace路徑api

    // 異常處理handle類
        'exception_handle'       => '\app\common\lib\exception\ApiHandleException',
  3. 在項目中新建文件:application\common\lib\exception\ApiException.php,restful

    <?php
    namespace app\common\lib\exception;
    use think\Exception;
    
    class ApiException extends Exception{
        public $message = '';
        public $httpCode = 500;
        public $code = 0;
        
        public function __construct($message = '', $httpCode = 0, $code = 0){
            $this->message = $message;
            $this->httpCode = $httpCode;
            $this->code = $code;
        }
    }
  4. 輸出異常例子數據結構

    public function test($status){
           if($status != 1){
               throw new ApiException('提交不合法', 400);
           } 
           return $status;
       }
相關文章
相關標籤/搜索