自定义异常类(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;
       }
相关文章
相关标签/搜索