hyperf:统一返回json格式

一,result类

<?php

/*
   统一格式的返回json数据
*/

namespace App\Lib\Result;

class Result
{
    //success:code值为0,data:数据
    static public function Success($data, $code = 200, $msg = '')
    {
        $rs = [
            'status' => 'success',
            'code' => $code,
            'time' => date('Y-m-d H:i:s'),
            'msg' => $msg,
            'data' => empty($data) ? (object)$data : $data,
        ];
        return response()->json($rs);
    }

    //Error:需要code/msg参数
    static public function Failed($code, $msg,$data=[])
    {

        $rs = [
            'status' => 'failed',
            'code' => $code,
            'time' => date('Y-m-d H:i:s'),
            'msg' => $msg,
            'data' => (object)$data,
        ];
        return response()->json($rs);
    }
}

response()函数:

if (! function_exists('response')) {
    /**
     * response 实例
     *
     * @return ResponseInterface|mixed
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    function response(): mixed
    {
        return container()->get(ResponseInterface::class);
    }
}

二,调用result类

1,controller中调用:

    public function imagedetail(RequestInterface $request, ResponseInterface $response) {
        $data = [
            'nickname' => $nickname,
        ];
        return Result::Success($data);
    }

2,在异常处理中配置:

app/Exception/Handler/HttpExceptionHandler.php

<?php


declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Exception\Handler;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\ExceptionHandler\Formatter\FormatterInterface;
use Hyperf\HttpMessage\Exception\HttpException;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Swow\Psr7\Message\ResponsePlusInterface;
use Throwable;

class HttpExceptionHandler extends ExceptionHandler
{
    public function __construct(protected StdoutLoggerInterface $logger, protected FormatterInterface $formatter)
    {
    }

    /**
     * Handle the exception, and return the specified result.
     * @param HttpException $throwable
     */
    public function handle(Throwable $throwable, ResponsePlusInterface $response)
    {
        $this->logger->debug($this->formatter->format($throwable));

        $this->stopPropagation();

        // 格式化输出,支掉了, JSON_UNESCAPED_UNICODE

        $data = json_encode([
            'status' => 'failed',
            'code' => $throwable->getCode(),
            'time' => date('Y-m-d H:i:s'),
            'message' => $throwable->getMessage(),
            'data' => (object)[],
        ]);
        //var_dump($data);
        //$data = Result::Failed($throwable->getCode(),$throwable->getMessage());

        return $response->setStatus($throwable->getStatusCode())->setBody(new SwooleStream($data));
    }

    /**
     * Determine if the current exception handler should handle the exception.
     *
     * @return bool If return true, then this exception handler will handle the exception,
     *              If return false, then delegate to next handler
     */
    public function isValid(Throwable $throwable): bool
    {
        return $throwable instanceof HttpException;
    }
}

三,测试效果:

posted @ 2025-02-15 11:08  刘宏缔的架构森林  阅读(66)  评论(0)    收藏  举报