/**
* 输出错误信息
* @param int $code
* @param $msg
* @throws BaseException
*/
protected function throwError($msg, $code = 0)
{
throw new BaseException(['code' => $code, 'msg' => $msg]);
}
/**
* 返回封装后的 API 数据到客户端
* @param int $code
* @param string $msg
* @param array $data
* @return array
*/
protected function renderJson($code = self::JSON_SUCCESS_STATUS, $msg = '', $data = [])
{
return compact('code', 'msg', 'url', 'data');
}
/**
* 返回操作成功json
* @param string $msg
* @param array $data
* @return array
*/
protected function renderSuccess($data = [], $msg = 'success')
{
return $this->renderJson(self::JSON_SUCCESS_STATUS, $msg, $data);
}
/**
* 返回操作失败json
* @param string $msg
* @param array $data
* @return array
*/
protected function renderError($msg = 'error', $data = [])
{
return $this->renderJson(self::JSON_ERROR_STATUS, $msg, $data);
}
class BaseException extends Exception {
public $code = 400;
public $msg = 'invalid parameters';
public $errorCode = 500;
/**
* 构造函数,接收一个关联数组
* @param array $params 关联数组只应包含code、msg和errorCode,且不应该是空值
*/
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'];
}
}
}
我想知道什么实用用异常类 我感觉都可以用 rendersuccess 返回数据吧 因为数据结构都一样的
可以像你说的那样。
但从语义的角度讲,明明是出错了,咋还能
success
呢?另外,可以拦截异常,单独做日志。