hf3.0使用枚举类
2023-07-31 本文已影响0人
geeooooz
转载自 “自如出博客” 地址:https://www.ziruchu.com/art/654
第一步:安装组件
composer require hyperf/constants
第二步:生成枚举类
php bin/hyperf.php gen:constant PostStatusCode
该命令会在 app/Constants
目录下生成 PostStatusCode.php
文件。
第三步:编写生成的枚举类
<?php
declare(strict_types=1);
namespace App\Constants;
use Hyperf\Constants\AbstractConstants;
use Hyperf\Constants\Annotation\Constants;
#[Constants]
class PostStatusCode extends AbstractConstants
{
/**
* @Message("草稿")
*/
const DRAFT = 1;
/**
* @Message("发布")
*/
const PUBLISHED = 2;
}
第四步:定义 API 异常类
1、定义异常 Handler
<?php
namespace App\Exception\Handler;
use App\Constants\ErrorCode;
use App\Constants\PostStatusCode;
use App\Exception\ApiException;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
use Throwable;
class ApiExceptionHandler extends ExceptionHandler
{
public function handle(Throwable $throwable, ResponseInterface $response)
{
if ($throwable instanceof ApiException) {
$data = json_encode([
'code' => $throwable->getCode(),
// 通过状态码获取枚举信息
'message' => PostStatusCode::getMessage($throwable->getCode()),
], JSON_UNESCAPED_UNICODE);
$this->stopPropagation();
return $response->withStatus(500)->withBody(new SwooleStream($data));
}
return $response;
}
public function isValid(Throwable $throwable): bool
{
return true;
}
}
2、定义异常
<?php
namespace App\Exception;
use Hyperf\Server\Exception\ServerException;
class ApiException extends ServerException
{
}
3、注册异常
<?php
// config/autoload/exceptions.php
declare(strict_types=1);
return [
'handler' => [
'http' => [
Hyperf\HttpServer\Exception\Handler\HttpExceptionHandler::class,
App\Exception\Handler\AppExceptionHandler::class,
// 添加 API 异常
\App\Exception\Handler\ApiExceptionHandler::class,
],
],
];
第五步:控制器使用枚举类
<?php
// App\Controller\demo\TestController.php
use App\Constants\PostStatusCode;
#[GetMapping('/test/error')]
public function error(RequestInterface $request)
{
$status = (int) $request->input('status', 1);
$code = match ($status) {
1 => PostStatusCode::DRAFT,
2 => PostStatusCode::PUBLISHED,
default => PostStatusCode::DRAFT,
};
throw new ApiException(PostStatusCode::getMessage($code), $code);
}
第六步:测试
$ curl http://192.168.31.90:9501/test/error?status=1
{"code":1,"message":"草稿"}
$ curl http://192.168.31.90:9501/test/error?status=2
{"code":2,"message":"发布"}