我正在创建一个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,它总是返回其类型属性,有没有一种方法,我可以实现我想要的结果?
1条答案
按热度按时间2w2cym1i1#
在您
web.php
中尝试将此代码添加到components