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.

39 lines
1.1 KiB

  1. <?php
  2. namespace App\Exception\Handler;
  3. use App\Constants\ErrorCode;
  4. use Hyperf\ExceptionHandler\ExceptionHandler;
  5. use Hyperf\HttpMessage\Stream\SwooleStream;
  6. use Hyperf\Validation\ValidationException;
  7. use Psr\Http\Message\ResponseInterface;
  8. // use Hyperf\Di\Annotation\Inject;
  9. // use Hyperf\HttpServer\Contract\ResponseInterface as Response;
  10. use Throwable;
  11. class ValidationExceptionHandler extends ExceptionHandler
  12. {
  13. // /**
  14. // * @Inject
  15. // * @var Response
  16. // */
  17. // private $reponse;
  18. public function handle(Throwable $throwable, ResponseInterface $response)
  19. {
  20. $this->stopPropagation();
  21. $content = json_encode([
  22. "status" => 'error',
  23. "code" => ErrorCode::PARAMS_INVALID,
  24. "result" => [],
  25. "message" => $throwable->validator->errors()->first()
  26. ]);
  27. return $response->withStatus($throwable->status)->withBody(new SwooleStream($content));
  28. }
  29. public function isValid(Throwable $throwable): bool
  30. {
  31. return $throwable instanceof ValidationException;
  32. }
  33. }