Skip to content

Commit

Permalink
refactor grpc error response
Browse files Browse the repository at this point in the history
  • Loading branch information
rauanmayemir committed Sep 9, 2024
1 parent a1d1265 commit 143cb1c
Showing 1 changed file with 15 additions and 18 deletions.
33 changes: 15 additions & 18 deletions src/Server.php
Original file line number Diff line number Diff line change
Expand Up @@ -82,13 +82,23 @@ public function serve(WorkerInterface $worker = null, callable $finalize = null)

$response = $this->invoke($call->service, $call->method, $context, $request->body);

/** @var ResponseHeaders|null $responseHeaders */
/** @var ?ResponseHeaders $responseHeaders */
$responseHeaders = $context->getValue(ResponseHeaders::class);
$responseHeadersString = $responseHeaders ? $responseHeaders->packHeaders() : '{}';

$this->workerSend($worker, $response, $responseHeadersString);
} catch (GRPCExceptionInterface $e) {
$this->workerGrpcError($worker, $context, $e);
/** @var ?ResponseHeaders $responseHeaders */
$responseHeaders = $context?->getValue(ResponseHeaders::class);

$this->workerSend(
$worker,
'',
Json::encode([
'error' => $this->createGrpcError($e),
'headers' => $responseHeaders->getHeaders(),
]),
);
} catch (\Throwable $e) {
$this->workerError($worker, $this->isDebugMode() ? (string)$e : $e->getMessage());
} finally {
Expand Down Expand Up @@ -128,11 +138,8 @@ private function workerSend(WorkerInterface $worker, string $body, string $heade
$worker->respond(new Payload($body, $headers));
}

private function workerGrpcError(
WorkerInterface $worker,
?ContextInterface $context,
GRPCExceptionInterface $e
): void {
private function createGrpcError(GRPCExceptionInterface $e): string
{
$status = new Status([
'code' => $e->getCode(),
'message' => $e->getMessage(),
Expand All @@ -147,17 +154,7 @@ static function ($detail) {
),
]);

/** @var ?ResponseHeaders $responseHeaders */
$responseHeaders = $context?->getValue(ResponseHeaders::class);

$this->workerSend(
$worker,
'',
Json::encode([
'error' => \base64_encode($status->serializeToString()),
'headers' => $responseHeaders->getHeaders(),
]),
);
return \base64_encode($status->serializeToString());
}

/**
Expand Down

0 comments on commit 143cb1c

Please sign in to comment.