feat : jwt

This commit is contained in:
2025-09-12 18:12:30 +08:00
parent a80c237bbb
commit ff3e0105ec
14 changed files with 362 additions and 38 deletions

View File

@@ -0,0 +1,57 @@
<?php
namespace App\Exception\Handler;
use App\Constants\ResultCode;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use Throwable;
use Lcobucci\JWT\Exception as JWTException;
class JwtExceptionHandler extends BaseErrExceptionHandler
{
/**
* @param Throwable $throwable
* @param ResponseInterface $response
* @return ResponseInterface
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function handle(Throwable $throwable, ResponseInterface $response): ResponseInterface
{
if ($throwable instanceof JWTException) {
$throwable = $this->modifyException($throwable);
// 传递给基类处理
return $this->handlerResponse($throwable, $response);
}
return $response;
}
protected function modifyException(Throwable $e): Throwable
{
// 根据不同的异常类型设置不同的code和message
switch ($e->getMessage()) {
case 'The token is expired':
$e->code = ResultCode::JWT_EXPIRED;
$e->message = 'token已过期';
break;
default:
$e->code = ResultCode::JWT_ERROR;
$e->message = 'token错误';
}
return $e;
}
/**
* @param Throwable $throwable
* @return bool
*/
public function isValid(Throwable $throwable): bool
{
return $throwable instanceof JWTException;
}
}