一、通用化API接口數據封裝
- 1、將下面代碼放到common.php公共文件中,方便調用
/**
* 通用化API接口數據輸出
* @param int $status 業務狀態碼
* @param string $message 信息提示
* @param [] $data 數據
* @param int $httpCode http狀態碼
* @return array
*/
function show($status, $message, $data=[], $httpCode=200) {
$data = [
'status' => $status,
'message' => $message,
'data' => $data,
];
return json($data, $httpCode);
}
return show(1, 'OK', $data, 200);
二、不可預知的內部異常api數據輸出解決方案
- 1、自定義ApiException繼承Exception
<?php
namespace app\common\lib\exception;
use think\Exception;
class ApiException extends Exception {
public $message = '';
public $httpCode = 500;
public $code = 0;
/**
* @param string $message
* @param int $httpCode
* @param int $code
*/
public function __construct($message = '', $httpCode = 0, $code = 0) {
$this->httpCode = $httpCode;
$this->message = $message;
$this->code = $code;
}
}
- 2、自定義ApiHandleException繼承Handle處理異常
<?php
namespace app\common\lib\exception;
use think\exception\Handle;
class ApiHandleException extends Handle {
/**
* http 狀態碼
* @var int
*/
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;
}
// 結合前面的通用化API接口數據封裝返回給前端
return show(0, $e->getMessage(), [], $this->httpCode);
}
}
- 3、替換系統自帶的Hanlder處理異常類
找到config.php
配置類,指向自己的ApiHandleException處理類
// 異常處理handle類 留空使用 \think\exception\Handle
'exception_handle' => '\app\common\lib\exception\ApiHandleException',
throw new ApiException('授權碼sign失敗', 401);