Files
hyperf_data/extend/Aether/PHP/Hyperf/RpcException/JsonRpcExceptionHandler.php
2025-09-28 14:51:38 +08:00

48 lines
1.6 KiB
PHP

<?php
declare(strict_types=1);
namespace Aether\RpcException;
use Hyperf\Context\ApplicationContext;
use Hyperf\Contract\ConfigInterface;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Hyperf\Rpc\Contract\ResponseInterface;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\MessageInterface;
use Throwable;
class JsonRpcExceptionHandler
{
/**
* JSON-RPC 异常处理.
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function handle(Throwable $throwable, ResponseInterface $response): MessageInterface|\Psr\Http\Message\ResponseInterface|ResponseInterface
{
$responseContents = $response->getBody()->getContents();
$responseContents = json_decode($responseContents, true);
if (! empty($responseContents['error'])) {
$port = null;
$config = ApplicationContext::getContainer()->get(ConfigInterface::class);
$servers = $config->get('server.servers');
foreach ($servers as $k => $server) {
if ($server['name'] == 'jsonrpc-http') {
$port = $server['port'];
break;
}
}
$responseContents['error']['message'] .= " - {$config->get('app_name')}:{$port}";
}
$data = json_encode($responseContents, JSON_UNESCAPED_UNICODE);
return $response->withStatus(200)->withBody(new SwooleStream($data));
}
public function isValid(Throwable $throwable): bool
{
return true;
}
}