| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- <?php
- declare(strict_types=1);
- /**
- * This file is part of Hyperf.
- *
- * @link https://www.hyperf.io
- * @document https://hyperf.wiki
- * @contact group@hyperf.io
- * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
- */
- namespace App\Exception\Handler;
- use Hyperf\Contract\StdoutLoggerInterface;
- use Hyperf\ExceptionHandler\ExceptionHandler;
- use Hyperf\HttpMessage\Stream\SwooleStream;
- use Phper666\JWTAuth\Exception\TokenValidException;
- use Psr\Http\Message\ResponseInterface;
- use Throwable;
- class AppExceptionHandler extends ExceptionHandler
- {
- /**
- * @var StdoutLoggerInterface
- */
- protected $logger;
- public function __construct(StdoutLoggerInterface $logger)
- {
- $this->logger = $logger;
- }
- public function handle(Throwable $throwable, ResponseInterface $response)
- {
- // 如果是授权异常
- if ($throwable instanceof TokenValidException) {
- // 格式化输出
- $message = $throwable->getMessage();
- $message = is_numeric($message)? __('api.'.$message) : $message;
- $data = json_encode([
- 'code' => __('api.'.$throwable->getCode()),
- 'message' => $message
- ], 256);
- // 阻止异常冒泡
- $this->stopPropagation();
- return $response->withBody(new SwooleStream($data));
- }
- $this->logger->error(sprintf('%s[%s] in %s', $throwable->getMessage(), $throwable->getLine(), $throwable->getFile()));
- $this->logger->error($throwable->getTraceAsString());
- return $response->withHeader('Server', 'Hyperf')->withStatus(500)->withBody(new SwooleStream('Internal Server Error.'));
- }
- public function isValid(Throwable $throwable): bool
- {
- return true;
- }
- }
|