hf3.0使用枚舉類

轉(zhuǎn)載自 “自如出博客” 地址: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("發(fā)布")
    */
   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(),
               // 通過狀態(tài)碼獲取枚舉信息
               '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":"發(fā)布"}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容