thinkphp6:自定义异常处理使统一返回json数据(thinkphp6.0.5 / php 7.4.9)
一,创建统一返回json格式数据的result类
app/business/Result/Result.php
<?php namespace app\business\Result; class Result { //success static public function Success($data) { $rs = [ 'code'=>0, 'msg'=>"success", 'data'=>$data, ]; return json($rs); } //error static public function Error($code,$msg) { $rs = [ 'code'=>$code, 'msg'=>$msg, 'data'=>"", ]; return json($rs); } }
说明:刘宏缔的架构森林是一个专注架构的博客,
网站:https://blog.imgtouch.com
本文: https://blog.imgtouch.com/index.php/2023/05/26/thinkphp6-zi-ding-yi-yi-chang-chu-li-shi-tong-yi-fan-hui/
对应的源码可以访问这里获取: https://github.com/liuhongdi/
说明:作者:刘宏缔 邮箱: 371125307@qq.com
二,测试效果:正常返回数据:
1,在controller中调用:
<?php namespace app\adm\controller; use app\BaseController; use app\business\Result\Result; class Index extends BaseController { //hello,demo public function hello($name = 'ThinkPHP6') { //return 'hello,' . $name; $data = array("name"=>$name,"str"=>"hello,".$name."!"); return Result::Success($data); } }
2,测试,访问:
http://127.0.0.1:81/adm/index/hello?name=laoliu
返回:
三,创建自定义的异常类,主要处理404/500等情况
app/business/Exception/MyException.php
<?php namespace app\business\Exception; use think\exception\Handle; use think\exception\HttpException; use think\exception\ValidateException; use think\Response; use Throwable; use ErrorException; use Exception; use InvalidArgumentException; use ParseError; //use PDOException; use think\db\exception\DataNotFoundException; use think\db\exception\ModelNotFoundException; use think\exception\ClassNotFoundException; use think\exception\HttpResponseException; use think\exception\RouteNotFoundException; use TypeError; use app\business\Result\Result; class MyException extends Handle { public function render($request, Throwable $e): Response { //如果处于调试模式 if (env('app_debug')){ //return Result::Error(1,$e->getMessage().$e->getTraceAsString()); return parent::render($request, $e); } // 参数验证错误 if ($e instanceof ValidateException) { return Result::Error(422,$e->getError()); } // 请求404异常 , 不返回错误页面 if (($e instanceof ClassNotFoundException || $e instanceof RouteNotFoundException) || ($e instanceof HttpException && $e->getStatusCode() == 404)) { return Result::Error(404,'当前请求资源不存在,请稍后再试'); } //请求500异常, 不返回错误页面 //$e instanceof PDOException || if ($e instanceof Exception || $e instanceof HttpException || $e instanceof InvalidArgumentException || $e instanceof ErrorException || $e instanceof ParseError || $e instanceof TypeError) { $this->reportException($request, $e); return Result::Error(500,'系统异常,请稍后再试'); } //其他错误 $this->reportException($request, $e); return Result::Error(1,"应用发生错误"); } //记录exception到日志 private function reportException($request, Throwable $e):void { $errorStr = "url:".$request->host().$request->url()."\n"; $errorStr .= "code:".$e->getCode()."\n"; $errorStr .= "file:".$e->getFile()."\n"; $errorStr .= "line:".$e->getLine()."\n"; $errorStr .= "message:".$e->getMessage()."\n"; $errorStr .= $e->getTraceAsString(); trace($errorStr, 'error'); } }
四,指定使用自定义异常类:
1,app/provider.php
指定'think\exception\Handle'的路径为自定义的MyException类的路径
<?php use app\ExceptionHandle; use app\Request; // 容器Provider定义文件 return [ 'think\Request' => Request::class, //'think\exception\Handle' => ExceptionHandle::class, 'think\exception\Handle' => '\\app\\business\\Exception\\MyException' ];
2,在一个controller的方法中加入除0代码,供测试用:
app/adm/controller/Index.php
<?php namespace app\adm\controller; use app\BaseController; use app\business\Result\Result; class Index extends BaseController { public function index() { $div = 0; $a = 100 / $div; $data = array("name"=>"liuhongdi","age"=>20); return Result::Success($data); } public function hello($name = 'ThinkPHP6') { //return 'hello,' . $name; $data = array("name"=>$name,"str"=>"hello,".$name."!"); return Result::Success($data); } }
五,测试效果
1,访问一个不存在的url,例如:
http://127.0.0.1:81/abcdef
返回:
2,访问包含除0错误的url:
http://127.0.0.1:81/adm/
返回:
六,查看thinkphp的版本
liuhongdi@ku:/data/php/mytp$ php think version v6.0.5
七,查看php的版本:
liuhongdi@ku:/data/logs/phplogs/tlog/202012$ php --version PHP 7.4.9 (cli) (built: Oct 26 2020 15:17:14) ( NTS ) Copyright (c) The PHP Group Zend Engine v3.4.0, Copyright (c) Zend Technologies with Zend OPcache v7.4.9, Copyright (c), by Zend Technologies