44 lines
1.2 KiB
PHP
44 lines
1.2 KiB
PHP
<?php
|
|
|
|
namespace App\Exception\Handler;
|
|
|
|
use Hyperf\ExceptionHandler\ExceptionHandler;
|
|
use Hyperf\HttpMessage\Stream\SwooleStream;
|
|
use Hyperf\Validation\ValidationException;
|
|
use Psr\Http\Message\ResponseInterface;
|
|
use Throwable;
|
|
|
|
/**
|
|
* 自定义验证器输出
|
|
*/
|
|
class ValidationExceptionHandler extends ExceptionHandler
|
|
{
|
|
/**
|
|
* handle.
|
|
* @param Throwable $throwable
|
|
* @param ResponseInterface $response
|
|
* @return ResponseInterface
|
|
*/
|
|
public function handle(Throwable $throwable, ResponseInterface $response)
|
|
{
|
|
$this->stopPropagation();
|
|
$keys = $throwable->validator->errors()->keys();
|
|
if (count($keys) > 0) {
|
|
$msg = $keys[0] . str_replace("validation", "", $throwable->validator->errors()->first($keys[0]));
|
|
} else {
|
|
$msg = $throwable->validator->errors()->first();
|
|
}
|
|
return $response->withStatus(200)->withBody(new SwooleStream(json_encode(['code'=>2,'msg'=>$msg])));
|
|
}
|
|
|
|
/**
|
|
* 验证之后
|
|
* @param Throwable $throwable
|
|
* @return bool
|
|
*/
|
|
public function isValid(Throwable $throwable): bool
|
|
{
|
|
return $throwable instanceof ValidationException;
|
|
}
|
|
}
|