AppExceptionHandler.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace App\Exception\Handler;
  12. use Hyperf\Contract\StdoutLoggerInterface;
  13. use Hyperf\ExceptionHandler\ExceptionHandler;
  14. use Hyperf\HttpMessage\Stream\SwooleStream;
  15. use Phper666\JWTAuth\Exception\TokenValidException;
  16. use Psr\Http\Message\ResponseInterface;
  17. use Throwable;
  18. class AppExceptionHandler extends ExceptionHandler
  19. {
  20. /**
  21. * @var StdoutLoggerInterface
  22. */
  23. protected $logger;
  24. public function __construct(StdoutLoggerInterface $logger)
  25. {
  26. $this->logger = $logger;
  27. }
  28. public function handle(Throwable $throwable, ResponseInterface $response)
  29. {
  30. // 如果是授权异常
  31. if ($throwable instanceof TokenValidException) {
  32. // 格式化输出
  33. $message = $throwable->getMessage();
  34. $message = is_numeric($message)? __('api.'.$message) : $message;
  35. $data = json_encode([
  36. 'code' => __('api.'.$throwable->getCode()),
  37. 'message' => $message
  38. ], 256);
  39. // 阻止异常冒泡
  40. $this->stopPropagation();
  41. return $response->withHeader('Server', 'Hyperf')->withStatus(401)->withBody(new SwooleStream($data));
  42. }
  43. $this->logger->error(sprintf('%s[%s] in %s', $throwable->getMessage(), $throwable->getLine(), $throwable->getFile()));
  44. $this->logger->error($throwable->getTraceAsString());
  45. return $response->withHeader('Server', 'Hyperf')->withStatus(500)->withBody(new SwooleStream('Internal Server Error.'));
  46. }
  47. public function isValid(Throwable $throwable): bool
  48. {
  49. return true;
  50. }
  51. }