12345678910111213141516171819202122232425262728293031323334353637383940414243444546 |
- <?php
- declare(strict_types=1);
- /**
- * This file is part of Hyperf.
- *
- * 表单验证器,异常处理器
- *
- * @link https://www.hyperf.io
- * @document https://hyperf.wiki
- * @contact group@hyperf.io
- * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
- */
- namespace App\Exception\Handler;
- use App\Utils\AppResult;
- use Hyperf\ExceptionHandler\ExceptionHandler;
- use Hyperf\HttpMessage\Stream\SwooleStream;
- use Hyperf\Validation\ValidationException;
- use Psr\Http\Message\ResponseInterface;
- use Throwable;
- class ValidationExceptionHandler extends ExceptionHandler
- {
- public function handle(Throwable $throwable, ResponseInterface $response)
- {
- $this->stopPropagation();
- // 统一返回格式
- return AppResult::error($throwable->validator->errors()->first());
- // /** @var \Hyperf\Validation\ValidationException $throwable */
- // $body = json_encode([
- // 'code' => 0,
- // 'msg' => $throwable->validator->errors()->first(),
- // 'data' => null
- // ], JSON_UNESCAPED_UNICODE);
- // if (!$response->hasHeader('content-type')) {
- // $response = $response->withAddedHeader('content-type', 'application/json; charset=utf-8');
- // }
- // return $response->withStatus(200)->withBody(new SwooleStream($body));
- }
- public function isValid(Throwable $throwable): bool
- {
- return $throwable instanceof ValidationException;
- }
- }
|