From ea6abe3043a73958aee6a7e97c008550c0217fec Mon Sep 17 00:00:00 2001 From: ctexthuang Date: Fri, 12 Sep 2025 18:21:19 +0800 Subject: [PATCH] feat : jwt --- app/Exception/Handler/JwtExceptionHandler.php | 18 +++++++++++++----- config/autoload/exceptions.php | 2 ++ 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/app/Exception/Handler/JwtExceptionHandler.php b/app/Exception/Handler/JwtExceptionHandler.php index 13bd7ca..921f0d7 100644 --- a/app/Exception/Handler/JwtExceptionHandler.php +++ b/app/Exception/Handler/JwtExceptionHandler.php @@ -3,6 +3,7 @@ namespace App\Exception\Handler; use App\Constants\ResultCode; +use App\Exception\ErrException; use Psr\Container\ContainerExceptionInterface; use Psr\Container\NotFoundExceptionInterface; use Psr\Http\Message\ResponseInterface; @@ -30,17 +31,24 @@ class JwtExceptionHandler extends BaseErrExceptionHandler return $response; } - protected function modifyException(Throwable $e): Throwable + protected function modifyException(JWTException $e): Throwable { // 根据不同的异常类型设置不同的code和message switch ($e->getMessage()) { case 'The token is expired': - $e->code = ResultCode::JWT_EXPIRED; - $e->message = 'token已过期'; + $code = ResultCode::JWT_EXPIRED; + $message = 'token已过期'; break; default: - $e->code = ResultCode::JWT_ERROR; - $e->message = 'token错误'; + $code = ResultCode::JWT_ERROR; + $message = 'token错误'; + } + + if (method_exists($e, 'setCustomCode')) { + $e->setCustomCode($code); + } + if (method_exists($e, 'setCustomMessage')) { + $e->setCustomMessage($message); } return $e; diff --git a/config/autoload/exceptions.php b/config/autoload/exceptions.php index 7a2bb31..92fc613 100644 --- a/config/autoload/exceptions.php +++ b/config/autoload/exceptions.php @@ -9,6 +9,7 @@ declare(strict_types=1); * @contact group@hyperf.io * @license https://github.com/hyperf/hyperf/blob/master/LICENSE */ + return [ 'handler' => [ 'http' => [ @@ -16,6 +17,7 @@ return [ App\Exception\Handler\ErrExceptionHandler::class, App\Exception\Handler\ValidationExceptionHandler::class, App\Exception\Handler\AppExceptionHandler::class, + App\Exception\Handler\JwtExceptionHandler::class, ], ], ];