45 lines
1.4 KiB
PHP
45 lines
1.4 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Exception\Handler;
|
|
|
|
use App\Constants\ErrorCode;
|
|
use App\Helper\Result;
|
|
use Hyperf\Context\Context;
|
|
use Hyperf\ExceptionHandler\ExceptionHandler;
|
|
use Hyperf\Validation\ValidationException;
|
|
use Hyperf\HttpMessage\Stream\SwooleStream;
|
|
use Hyperf\JsonRpc\DataFormatter;
|
|
use Psr\Http\Message\ResponseInterface;
|
|
use Psr\Http\Message\ServerRequestInterface;
|
|
use Throwable;
|
|
|
|
class ValidateExceptionHandler extends ExceptionHandler
|
|
{
|
|
public function handle(Throwable $throwable, ResponseInterface $response)
|
|
{
|
|
$this->stopPropagation();
|
|
$babMessages = $throwable->validator->errors();
|
|
$message = $babMessages->first();
|
|
$error = explode('|', $message, 2);
|
|
$code = $error[1] ?? ErrorCode::COMMON_ERROR;
|
|
$data = Result::error($code, $error[0]);
|
|
|
|
$dataFormatter = make(DataFormatter::class);
|
|
$request = Context::get(ServerRequestInterface::class);
|
|
$id = $request->getAttribute('request_id');
|
|
$result = $dataFormatter->formatResponse([$id, $data]);
|
|
$responseStr = json_encode($result, JSON_UNESCAPED_UNICODE);
|
|
|
|
return $response->withHeader('Content-Type', 'application/json')->withBody(new SwooleStream($responseStr));
|
|
}
|
|
|
|
/**
|
|
* 判断该异常处理器是否要对该异常进行处理
|
|
*/
|
|
public function isValid(Throwable $throwable): bool
|
|
{
|
|
return $throwable instanceof ValidationException;
|
|
}
|
|
} |