mirror of
https://gitee.com/ctexthuang/hyperf_rbac_framework_server_ctexthuang.git
synced 2025-12-25 17:07:49 +08:00
feat : jwt
This commit is contained in:
57
app/Exception/Handler/JwtExceptionHandler.php
Normal file
57
app/Exception/Handler/JwtExceptionHandler.php
Normal 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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user