thinkphp6:自定义异常处理使统一返回json数据(thinkphp6.0.5 / php 7.4.9)

一,创建统一返回json格式数据的result类

app/business/Result/Result.php

<?php
namespace appusinessResult;

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://www.cnblogs.com/architectforest

         对应的源码可以访问这里获取: https://github.com/liuhongdi/

说明:作者:刘宏缔 邮箱: 371125307@qq.com

二,测试效果:正常返回数据:

1,在controller中调用:

<?php
namespace appadmcontroller;

use appBaseController;
use appusinessResultResult;

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 appusinessException;

use thinkexceptionHandle;
use thinkexceptionHttpException;
use thinkexceptionValidateException;
use thinkResponse;
use Throwable;
use ErrorException;
use Exception;
use InvalidArgumentException;
use ParseError;
//use PDOException;
use thinkdbexceptionDataNotFoundException;
use thinkdbexceptionModelNotFoundException;
use thinkexceptionClassNotFoundException;
use thinkexceptionHttpResponseException;
use thinkexceptionRouteNotFoundException;
use TypeError;
use appusinessResultResult;

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()."
";
        $errorStr .= "code:".$e->getCode()."
";
        $errorStr .= "file:".$e->getFile()."
";
        $errorStr .= "line:".$e->getLine()."
";
        $errorStr .= "message:".$e->getMessage()."
";
        $errorStr .=  $e->getTraceAsString();

        trace($errorStr, 'error');
    }

}

四,指定使用自定义异常类:

1,app/provider.php

指定'thinkexceptionHandle'的路径为自定义的MyException类的路径

<?php
use appExceptionHandle;
use appRequest;

// 容器Provider定义文件
return [
    'thinkRequest'          => Request::class,
    //'thinkexceptionHandle' => ExceptionHandle::class,
    'thinkexceptionHandle'       => '\app\business\Exception\MyException'
];

2,在一个controller的方法中加入除0代码,供测试用:

app/adm/controller/Index.php

<?php
namespace appadmcontroller;

use appBaseController;
use appusinessResultResult;

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
原文地址:https://www.cnblogs.com/architectforest/p/14187878.html