ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
1.更改`app\lib\exception`下ExceptionHandler.php文件 ~~~ <?php namespace app\lib\exception; use Exception; use think\exception\Handle; use think\Request; use think\Log; class ExceptionHandler extends Handle { private $code; private $msg; private $errorCode; public function render(Exception $e) { if ($e instanceof BaseException) { //如果是自定义异常,则控制http状态码,不需要记录日志 //因为这些通常是因为客户端传递参数错误或者是用户请求造成的异常 //不应当记录日志 $this->code = $e->code; $this->msg = $e->msg; $this->errorCode = $e->errorCode; } else{ // 如果是服务器未处理的异常,将http状态码设置为500,并记录日志 if(config('app_debug')){ // 调试状态下需要显示TP默认的异常页面,因为TP的默认页面 // 很容易看出问题 return parent::render($e); } // 如果是服务器未处理的异常,将http状态码设置为500,并记录日志 $this->code = 500; $this->msg = 'sorry,we make a mistake. (^o^)Y'; $this->errorCode = 999; $this->recordErrorLog($e); } $request = Request::instance(); $result = [ 'msg' => $this->msg, 'error_code' => $this->errorCode, 'request_url' => $request = $request->url() ]; return json($result, $this->code); } /* * 将异常写入日志 */ private function recordErrorLog(Exception $e) { Log::init([ 'type' => 'File', 'path' => LOG_PATH, 'level' => ['error'] ]); // Log::record($e->getTraceAsString()); Log::record($e->getMessage(),'error'); } } ~~~ 2.在`app\lib\exception`下新建ParameterException.php文件 ~~~ <?php namespace app\lib\exception; /** * 通用参数类异常错误 */ class ParameterException extends BaseException { public $code = 400; public $errorCode = 10000; public $msg = "invalid parameters"; } ~~~ 3.修改验证器中BaseValidate.php文件 ~~~ <?php namespace app\api\validate; use app\lib\exception\ParameterException; use think\Exception; use think\Request; use think\Validate; class BaseValidate extends Validate { public function goCheck() { // 获取http传入的参数 // 对这些参数做检验 $request = Request::instance(); $params = $request->param(); $result = $this->check($params); if(!$result){ $e =new ParameterException(); $e->msg=$this->error; throw $e; //$error = $this->error; //throw new Exception($error); } else{ return true; } } } ~~~ 结果 ![](https://box.kancloud.cn/6f7f55132a97bb6870defaff4c38996a_1054x552.png)