配置文件修改
config/app.php
自定义非常接受类出处
'exception_handle' => ‘\app\common\exception\ExceptionHandle',
自定义处理惩罚非常方法
寡人的存放目次为 app/common/exception
ApiException.php
- namespace app\common\exception;
- use Exception;
- class ApiException extends Exception
- {
- /**
- * 构造函数
- */
- public function __construct(array $ApiErrConst, Throwable $previous = null)
- {
- $code = $ApiErrConst[0];
- $message = $ApiErrConst[1];
- parent::__construct($message, $code, $previous);
- }
- }
复制代码
ExceptionHandle.php
- namespace app\common\exception;
- use Exception;
- use think\exception\Handle;
- use app\common\exception\ApiException;
- use app\common\err\ApiErrCode;
- class ExceptionHandle extends Handle
- {
- // 引入复用模块:JSON返回格式
- use \app\common\traits\ResponseJson;
- public function render(Exception $e)
- {
- if($e instanceof ApiException) {
- $code = $e->getCode();
- $message = $e->getMessage();
- }else{
- $code = $e->getCode();
- if(!$code || $code < 0) {
- $code = ApiErrCode::ERROR_UNKNOW[0];
- }
- $message = $e->getMessage() ? $e->getMessage() : ApiErrCode::ERROR_UNKNOW[1];
- }
- echo $this->jsonErrorData($code,$message); //该方法在下方
- // 其他错误交给系统处理
- // return parent::render($e);
- }
- }
复制代码
错误码文件
存放目次:app/common/err- namespace app\common\err;
- class ApiErrCode
- {
- /**
- * API通用错误码 const 定义常量
- * error_code < 1000
- */
- const ERROR_UNKNOW = [0, "未知错误"];
- const ERROR_URL = [1, "接口不存在"];
- .......
- }
复制代码
复用模块
针对API接口返回格式
存放目次:app/common/traits- namespace app\common\traits;
- trait ResponseJson
- {
- /**
- * API接口出现业务异常时时返回
- * @author Leo
- */
- public function jsonErrorData($code,$message,$data = [])
- {
- return $this->jsonResponse($code, $message, $data);
- }
-
- /**
- * API接口请求成功时返回
- * @author Leo
- */
- public function jsonSuccessData($data = [])
- {
- return $this->jsonResponse(200, "Sucess", $data);
- }
-
- /**
- * 返回一个JSON
- * @author Leo
- */
- private function jsonResponse($code,$message,$data)
- {
- $content = [
- 'code' => $code,
- 'msg' => $message,
- 'data' => $data
- ];
- return json_encode($content);
- }
- }
复制代码
页面调用
- // 文件头部引入
- use app\common\exception\ApiException;
- use app\common\err\ApiErrCode;
- // 引入复用模块:JSON返回格式
- use \app\common\traits\ResponseJson;
-
- // 示例
- public function index() {
- throw new ApiException(ApiErrCode::ERROR_URL); // 自定义异常抛出
- }
复制代码
到此这篇关于thinkphp5.1 中使用自定义非常处理惩罚类举行接受的文章就先容到这了,更多相关thinkphp5.1 自定义非常处理惩罚类内容请搜刮脚本之家从前的文章或继续浏览下面的相关文章渴望各人以后多多支持脚本之家! |