为了方便tp5.1框架输出报错信息看起来简单,在这里把输出信息修改(个人想法,不喜勿喷)
打开thinkphp->library->think->response->Json.php 找到output方法try{ }里面,添加
//引入Config use think/facade/Config; if(Config::get('api_return_standard')){ $data = $this->standard($data); if(!$data){ return; } }
新建方法 standard
public function standard($data) { if(!isset($data[0]) || !is_int($data[0]) || !isset($data[1])){ echo '数据格式错误<pre>'; print_r($data); echo '</pre>'; return false; } if(200 === $data[0]){ return ['ret' => 200,'data' => $data[1],'msg'=>'']; } return ['ret' => $data[0],'data' => [],'msg' => $data[1]]; }
这个可以把 return [501,'数据错误']; 自动变换
{"ret":501,"data":[],"msg":"数据错误"}
打开thinkphp->library->exception->Handle.php 找到convertExceptionToResponse 方法
在$content = ob_get_clean(); 下面添加
if(!Container::get('app')->config('api_return_standard')){ include Container::get('app')->config('exception_tmpl'); $response = Response::create($content,'html'); }else{ $response = Response::create([ 'namespace' => get_class($exception), 'file' => $exception->getFile(), 'line' => $exception->getLine(), 'message' => $this->getMessage($exception), ],'json'); }
在出现错误是 格式如下