You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
hyperf-gateway/app/Exception/Handler/ValidateExceptionHandler.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;
}
}