ValidationExceptionHandler.php 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * 表单验证器,异常处理器
  7. *
  8. * @link https://www.hyperf.io
  9. * @document https://hyperf.wiki
  10. * @contact group@hyperf.io
  11. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  12. */
  13. namespace App\Exception\Handler;
  14. use App\Utils\AppResult;
  15. use Hyperf\ExceptionHandler\ExceptionHandler;
  16. use Hyperf\HttpMessage\Stream\SwooleStream;
  17. use Hyperf\Validation\ValidationException;
  18. use Psr\Http\Message\ResponseInterface;
  19. use Throwable;
  20. class ValidationExceptionHandler extends ExceptionHandler
  21. {
  22. public function handle(Throwable $throwable, ResponseInterface $response)
  23. {
  24. $this->stopPropagation();
  25. /** @var \Hyperf\Validation\ValidationException $throwable */
  26. $body = json_encode([
  27. 'code' => 0,
  28. 'msg' => $throwable->validator->errors()->first(),
  29. 'data' => null
  30. ], JSON_UNESCAPED_UNICODE);
  31. if (!$response->hasHeader('content-type')) {
  32. $response = $response->withAddedHeader('content-type', 'application/json; charset=utf-8');
  33. }
  34. return $response->withStatus(200)->withBody(new SwooleStream($body));
  35. }
  36. public function isValid(Throwable $throwable): bool
  37. {
  38. return $throwable instanceof ValidationException;
  39. }
  40. }