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.

34 lines
950 B

  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 Throwable;
  9. class ValidationExceptionHandler extends ExceptionHandler
  10. {
  11. public function handle(Throwable $throwable, ResponseInterface $response)
  12. {
  13. $this->stopPropagation();
  14. $content = json_encode([
  15. "status" => 'error',
  16. "code" => ErrorCode::PARAMS_INVALID,
  17. "result" => [],
  18. "message" => $throwable->validator->errors()->first()
  19. ]);
  20. return $response->withHeader('Content-Type', 'application/json')
  21. ->withStatus(200)
  22. ->withBody(new SwooleStream($content));
  23. }
  24. public function isValid(Throwable $throwable): bool
  25. {
  26. return $throwable instanceof ValidationException;
  27. }
  28. }