TokenValidExceptionHandler.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * JWT token valid
  5. * @author wesmiler
  6. */
  7. namespace App\Exception\Handler;
  8. use Hyperf\Contract\StdoutLoggerInterface;
  9. use Hyperf\ExceptionHandler\ExceptionHandler;
  10. use Hyperf\HttpMessage\Stream\SwooleStream;
  11. use Phper666\JWTAuth\Exception\TokenValidException;
  12. use Psr\Http\Message\ResponseInterface;
  13. use Throwable;
  14. class TokenValidExceptionHandler extends ExceptionHandler
  15. {
  16. /**
  17. * @var StdoutLoggerInterface
  18. */
  19. protected $logger;
  20. public function __construct(StdoutLoggerInterface $logger)
  21. {
  22. $this->logger = $logger;
  23. }
  24. public function handle(Throwable $throwable, ResponseInterface $response)
  25. {
  26. // 判断被捕获到的异常是希望被捕获的异常
  27. if ($throwable instanceof TokenValidException) {
  28. // 格式化输出
  29. $message = $throwable->getMessage();
  30. $message = is_numeric($message)? __('api.'.$message) : $message;
  31. $data = json_encode([
  32. 'code' => __('api.'.$throwable->getCode()),
  33. 'message' => $message
  34. ], 256);
  35. // 阻止异常冒泡
  36. $this->stopPropagation();
  37. return $response->withBody(new SwooleStream($data));
  38. }
  39. // 交给下一个异常处理器
  40. return $response;
  41. }
  42. public function isValid(Throwable $throwable): bool
  43. {
  44. return true;
  45. }
  46. }