ValidationExceptionHandler.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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. // 统一返回格式
  26. return AppResult::error($throwable->validator->errors()->first());
  27. // /** @var \Hyperf\Validation\ValidationException $throwable */
  28. // $body = json_encode([
  29. // 'code' => 0,
  30. // 'msg' => $throwable->validator->errors()->first(),
  31. // 'data' => null
  32. // ], JSON_UNESCAPED_UNICODE);
  33. // if (!$response->hasHeader('content-type')) {
  34. // $response = $response->withAddedHeader('content-type', 'application/json; charset=utf-8');
  35. // }
  36. // return $response->withStatus(200)->withBody(new SwooleStream($body));
  37. }
  38. public function isValid(Throwable $throwable): bool
  39. {
  40. return $throwable instanceof ValidationException;
  41. }
  42. }