在Yii2或原生PHP中创建Costume可抛出类

6g8kf2rb  于 2023-05-27  发布在  PHP
关注(0)|答案(1)|浏览(127)

我正在创建一个API,但是我想创建一个Throwable类,例如我想执行像throw new Response(400, 'Invalid Token')这样的东西,我想像这样返回

{
  "code": 400,
  "message": "Invalid Token"
}

我尝试将类扩展为Error或Throwable类,但结果总是返回堆栈跟踪,行等。

<?php

namespace app\modules\scoring\components;

use Yii;

class Response extends \Exception implements \Throwable {

  public $httpCode;
  public $message;

  public static function set(int $http, array $data = []) {
    $data = \yii\helpers\ArrayHelper::merge($data, [
      'server_time' => date('Y-m-d H:i:s')
    ]);
    Yii::$app->response->statusCode = $http;
    $old = isset(Yii::$app->response->data) ? Yii::$app->response->data : [];
    return Yii::$app->response->data = array_merge($old, $data);
  }

  public static function setNonAjaxRequestError() {
    return self::set(400, [
      'code' => 400,
      'message' => 'Request Must Use HttpRequest'
    ]);
  }

  public function __construct($httpCode, $message) {
    unset($this->line);
    $this->httpCode = $httpCode;
    $this->message = $message;
  }

}

尝试使用yii2类,如HttpException,它总是返回其类型属性,有没有一种方法,我可以实现我想要的结果?

2w2cym1i

2w2cym1i1#

在您web.php中尝试将此代码添加到components

'response' => [
            'format' => yii\web\Response::FORMAT_JSON,
            'charset' => 'UTF-8',
            'class' => 'yii\web\Response',
            'on beforeSend' => function ($event) {
                $response = $event->sender;
                if ($response->format === 'json' && $response->statusCode !== 200 && $response->statusCode !== 302) {
                    $response->data = [
                        'code' => $response->statusCode,
                        'message' => $response->data['message'] ?? 'System error',
                    ];
                }
            },
        ],

相关问题