1234567891011121314151617181920212223242526272829303132333435363738394041424344 |
- <?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();
- /** @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;
- }
- }
|