thinkphp6:⾃定义异常处理使统⼀返回json数据(thinkphp6.0.5php。。
。
⼀,创建统⼀返回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);
}
}
说明:刘宏缔的架构森林是⼀个专注架构的博客,地址:
对应的源码可以访问这⾥获取:
说明:作者:刘宏缔邮箱: 371125307@qq
⼆,测试效果:正常返回数据:
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,测试,访问:
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,
phpjson格式化输出//'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,例如:
127.0.0.1:81/abcdef
返回:
2,访问包含除0错误的url:
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
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论