1. 首先在application目录下新建一个/lib/exception 文件夹存放异常类
    2. 在该异常类文件夹中新建ExceptionHandler.php文件 ```javascript namespace app\lib\exception; use Exception; use think\exception\Handle;

    class ExceptionHandler extends Handle { public $code; public $msg; public $errorCode; public function render(Exception $e) { //判断$e的对象是否属于BaseException类的实例参数 if($e instanceof BaseException){ $this->code=$e->code; $this->msg=$e->msg; $this->errorCode=$e->errorCode; }else{ //判断是否为开发模式,是的话就传给父类执行抛出异常 if(config(‘app.app_debug’))return parent::render($e); $this->code=500; $this->msg=”服务器异常”; $this->errorCode=”999”; } $res=[ “code”=>$this->code, “msg”=>$this->msg, “errorCode”=>$this->errorCode ];

    1. return json($res,$this->code);
    2. }

    }

    1. 3.在该异常类文件夹中新建BaseException.php文件
    2. ```javascript
    3. namespace app\lib\exception;
    4. use think\Exception;
    5. class BaseException extends Exception
    6. {
    7. public $code=400;
    8. public $msg="系统错误";
    9. public $errorCode=999;
    10. public function __construct($params=[])
    11. {
    12. if(!is_array($params))return;
    13. if(array_key_exists('code',$params)) $this->code=$params['code'];
    14. if(array_key_exists('msg',$params)) $this->msg=$params['msg'];
    15. if(array_key_exists('errorCode',$params)) $this->errorCode=$params['errorCode'];
    16. }
    17. }

    4.最后进行调试

    1. namespace app\index\controller;
    2. use app\lib\exception\BaseException;
    3. use think\Controller;
    4. use think\Request;
    5. class Index extends Controller
    6. {
    7. public function index()
    8. {
    9. throw new BaseException(['code'=>"401",'msg'=>"错误"]);
    10. }
    11. }

    5.展示结果

    1. {"code":"401","msg":"错误","errorCode":999}