48 lines
1.4 KiB
PHP
48 lines
1.4 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();
|
|
/** @var \Hyperf\Validation\ValidationException $throwable */
|
|
$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();
|
|
}
|
|
if (!$response->hasHeader('content-type')) {
|
|
$response = $response->withAddedHeader('content-type', 'application/json; charset=utf-8');
|
|
}
|
|
return $response->withStatus(200)->withBody(new SwooleStream(json_encode(['code'=>1,'msg'=>$msg])));
|
|
}
|
|
|
|
/**
|
|
* 验证之后
|
|
* @param Throwable $throwable
|
|
* @return bool
|
|
*/
|
|
public function isValid(Throwable $throwable): bool
|
|
{
|
|
return $throwable instanceof ValidationException;
|
|
}
|
|
}
|