在公用的common.php中创建show方法,客户端调用服务器端接口返回json数据
/*
* 通用化API接口数据输出
*/
function show($status, $message, $data = [], $httpCode = 200){
$data = [
'status' => $status,
'message' => $message,
'data' => $data,
];
return json($data, $httpCode);
}
在app/common/lib/exception/创建ApiException类
<?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->httpCode = $httpCode;
$this->message = $message;
$this->code = $code;
}
}
在app/common/lib/exception/创建ApiHandleException类,让服务器端返回json格式的错误
<?php
namespace app\common\lib\exception;
use think\exception\Handle;
class ApiHandleException extends Handle
{
/*
* http状态码
*/
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;
}
return show(0, $e->getMessage(), [], $this->httpCode);
}
}
修改config.php配置文件
测试:
在控制器中输入如下代码:
public function save(){
$data = input('post.');
if($data['mt'] != 1){
throw new ApiException('您提交的数据不合法', 400);
}
return show(1, 'OK', input('post.'), 201);
}
postman中调用该方法
app_debug为true时返回下图时代码生效
app_debug为false时返回下图时代码生效