TP5 handles unpredictable internal abnormal api data output solution

Create the show method in the public common.php, and the client calls the server-side interface to return json data

/*
 * 通用化API接口数据输出
 */
function show($status, $message, $data = [], $httpCode = 200){
    $data = [
        'status' => $status,
        'message' => $message,
        'data' => $data,
    ];
    return json($data, $httpCode);
}

Create ApiException class in app/common/lib/exception/

<?php


namespace app\common\lib\exception;


use think\Exception;

class ApiException extends Exception
{
    public $message = '';
    public $httpCode = 500;
    public $code = 0;

    public function __construct($message = "", $httpCode = 0, $code = 0)
    {
        $this->httpCode = $httpCode;
        $this->message = $message;
        $this->code = $code;
    }
}

Create an ApiHandleException class in app/common/lib/exception/ to let the server return an error in json format

<?php


namespace app\common\lib\exception;


use think\exception\Handle;

class ApiHandleException extends Handle
{
    /*
     * http状态码
     */
    public $httpCode = 500;
    public function render(\Exception $e)
    {
        if(config('app_debug') == true){
            return parent::render($e);
        }
        if($e instanceof ApiException){
            $this->httpCode = $e->httpCode;
        }
        return show(0, $e->getMessage(), [], $this->httpCode);
    }

}

Modify the config.php configuration file

 test:

Enter the following code in the controller:

public function save(){
        $data = input('post.');
        if($data['mt'] != 1){
            throw new ApiException('您提交的数据不合法', 400);
        }

        return show(1, 'OK', input('post.'), 201);
    }

Call this method in postman

When app_debug is true, the code will take effect when the following figure is returned

When app_debug is false, the code will take effect when the following figure is returned 

Guess you like

Origin blog.csdn.net/qq_43737121/article/details/105637554