mirror of
https://gitee.com/ctexthuang/hyperf_rbac_framework_server_ctexthuang.git
synced 2025-12-26 02:17:48 +08:00
69 lines
1.9 KiB
PHP
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;
|
|
}
|
|
} |