Files
hyperf_rbac_framework_serve…/app/Exception/Handler/JwtExceptionHandler.php
2025-09-12 23:54:03 +08:00

69 lines
1.9 KiB
PHP

<?php
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;
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;
}
/**
* @param JWTException $e
* @return ErrException
*/
protected function modifyException(JWTException $e): ErrException
{
// 根据不同的异常类型设置不同的code和message
switch ($e->getMessage()) {
case 'The token is expired':
$code = ResultCode::JWT_EXPIRED;
$message = 'token已过期';
break;
default:
$code = ResultCode::JWT_ERROR;
$message = 'token错误';
}
if (method_exists($e, 'setCustomCode')) {
$e->setCustomCode($code);
}
if (method_exists($e, 'setCustomMessage')) {
$e->setCustomMessage($message);
}
return New ErrException($message,$code);
}
/**
* @param Throwable $throwable
* @return bool
*/
public function isValid(Throwable $throwable): bool
{
return $throwable instanceof JWTException;
}
}