- 首先在application目录下新建一个/lib/exception 文件夹存放异常类
- 在该异常类文件夹中新建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 ];
return json($res,$this->code);}
}
3.在该异常类文件夹中新建BaseException.php文件```javascriptnamespace app\lib\exception;use think\Exception;class BaseException extends Exception{public $code=400;public $msg="系统错误";public $errorCode=999;public function __construct($params=[]){if(!is_array($params))return;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'];}}
4.最后进行调试
namespace app\index\controller;use app\lib\exception\BaseException;use think\Controller;use think\Request;class Index extends Controller{public function index(){throw new BaseException(['code'=>"401",'msg'=>"错误"]);}}
5.展示结果
{"code":"401","msg":"错误","errorCode":999}
