自定义返回json处理

旧城·离人·半城烟
新建exception文件夹,新增文件Handle.php文件
<?php

namespace App\service\exception;

use Webman\Exception\ExceptionHandler;
use Webman\Http\Request;
use Webman\Http\Response;
use Throwable;

class Handler extends ExceptionHandler
{
    /**
     * 不用记录日志的异常
     * @var string[]
     */
    public $dontReport = [
        HttpException::class
    ];

    public function report(Throwable $exception)
    {
        parent::report($exception);
    }

    public function render(Request $request, Throwable $exception) : Response
    {
        if ($exception instanceof HttpException) {
            return $exception->getResponse();
        }
        if ($request->expectsJson()) {
            if (!$this->_debug) {
                $json = ['code' => 500, 'msg' => '服务器错误!'];
                return new Response(200, ['Content-Type' => 'application/json'],
                    json_encode($json, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
            }
        }
        return parent::render($request, $exception);
    }
}

新增文件HttpException.php文件
<?php

namespace App\service\exception;

use support\Response;
use Throwable;

class HttpException extends \RuntimeException
{
    protected $response = null;

    public function __construct($message = "", $code = 0, $header=[],Throwable $previous = null)
    {
        $this->response = json(json_decode($message,true));
        parent::__construct($message, $code, $previous);
    }

    public function getResponse(){
        return $this->response;
    }
}

新增Jump.php
<?php

namespace App\service\common;

use App\service\exception\HttpException;

trait  Jump
{
    static protected $return_code = [
        1001 => '请求成功',
        1002 => '你想做什么呢', //非法的请求方式 非ajax
        1003 => '请求参数错误', //如参数不完整,类型不正确
        1004 => '请先登陆再访问', //未登录 或者 未授权
        1005 => '请求授权不符', ////非法的请求  无授权查看
        1006 => '数据加载失败', //
        1007 => '拒绝请求',//禁止访问的方法
        1008 => '当前访问路由不存在',//miss路由
        1009 => '验证码错误!',
        1010 => '数据不存在', //
        1020 => '验证码输入不正确', //
        1021 => '用户账号或密码错误', //
        1022 => '用户账号被禁用', //
        1030 => '数据操作失败', //
        1031 => '成功移除数据',
        1032 => '请输入管理密码',
        1033 => '管理密码错误',
        1034 => '邮件发送成功!',
        1035 => '邮件发送失败!',
        1040 => '网站未开放!',
        1041 => '未开放注册!',
        1042 => '接口未开放!',
        1043 => '结算功能未开放!',
        1044 => '退款功能未开放!',
    ];
    protected $back = [];//返回的数据

    /**
     * Notes:错误返回方式
     * User: Administrator
     * DateTime: 2022/3/30 22:20
     * @param string $message
     * @param int $code
     * @param int $status
     * @param string $type
     * @param array $header
     */
    protected function error($message = '', int $code = 412, int $status = 0, $header = [])
    {
        $res_msg = self::$return_code;
        $message = is_string($message) && !empty($message) ? $message : $res_msg[$message] ?? "未定义消息!";
        $data = [
            'data' => $this->back,
            'msg'=>$message,
            'code' => $code,
            'status' => $status,
            'time' => time()
        ];
        throw  new HttpException(json_encode($data, JSON_UNESCAPED_UNICODE),$code,$header);
    }

    /**
     * Notes:成功返回方式
     * User: Administrator
     * DateTime: 2022/3/30 22:21
     * @param string $message
     * @param int $code
     * @param int $status
     * @param string $type
     * @param array $header
     */
    protected function success($message = '', int $code = 200, int $status=1,string $type = 'json', $header = [])
    {

        $message = is_string($message) && !empty($message) ? $message : self::$return_code[$message] ?? self::$return_code[1001];
        $data = [
            'msg'=>$message,
            'data' => $this->back,
            'code' => $code,
            'status' => $status,
            'time' => time()
        ];
        throw new HttpException( json_encode($data, JSON_UNESCAPED_UNICODE), $code,  $header);

    }

    /**
     * Notes:返回数据  不做跳转
     * User: Administrator
     * DateTime: 2022/3/30 22:21
     * @param string $message
     * @param int $code
     * @param array $data
     * @return array
     */
    protected function back(string $message, int $code = 0, $data = [] ) :array
    {
        $back = [
            'message' => $message, 'code' => $code, 'data' => $data
        ];
        return $back;
    }
}

调用的时候use Jump即可
$this->error();
$this-success();
1632 2 1
2个评论

有什么问题,大家可以提下,互相切磋探讨

$this->back = $data;//需要返回参数
$this->success();

  • xiaodong 2022-09-06

    如果 控制器写了 try catch 那$this->success 岂不是也作为异常给抛出了?

年代过于久远,无法发表评论

旧城·离人·半城烟

856
积分
0
获赞数
0
粉丝数
2019-12-04 加入
×
🔝