You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

47 lines
1.3 KiB

  1. <?php
  2. namespace App\Exception\Handler;
  3. use App\Exception\ErrorCodeException;
  4. use Hyperf\Contract\StdoutLoggerInterface;
  5. use Hyperf\ExceptionHandler\ExceptionHandler;
  6. use Hyperf\HttpMessage\Stream\SwooleStream;
  7. use Psr\Http\Message\ResponseInterface;
  8. use Throwable;
  9. class ErrorCodeExceptionHandler extends ExceptionHandler
  10. {
  11. /**
  12. * @var StdoutLoggerInterface
  13. */
  14. protected $logger;
  15. public function __construct(StdoutLoggerInterface $logger)
  16. {
  17. $this->logger = $logger;
  18. }
  19. public function handle(Throwable $throwable, ResponseInterface $response)
  20. {
  21. $this->logger->error(sprintf('%s[%s] in %s', $throwable->getMessage(), $throwable->getLine(), $throwable->getFile()));
  22. $this->logger->error($throwable->getTraceAsString());
  23. $this->stopPropagation();
  24. $content = json_encode([
  25. "status" => 'error',
  26. "code" => $throwable->getCode(),
  27. "result" => [],
  28. "message" => $throwable->getMessage()
  29. ]);
  30. return $response->withHeader('Content-Type', 'application/json')
  31. ->withStatus(200)
  32. ->withBody(new SwooleStream($content));
  33. }
  34. public function isValid(Throwable $throwable): bool
  35. {
  36. return $throwable instanceof ErrorCodeException;
  37. }
  38. }