Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Expose errors with the correct protobuf type #611

Open
wants to merge 16 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 67 additions & 8 deletions src/ApiException.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ class ApiException extends Exception
private $metadata;
private $basicMessage;
private $decodedMetadataErrorInfo;
private array $protobufErrors;

/**
* ApiException constructor.
Expand All @@ -62,7 +63,8 @@ public function __construct(
string $message,
int $code,
?string $status = null,
array $optionalArgs = []
array $optionalArgs = [],
array $protobufErrors = [],
) {
$optionalArgs += [
'previous' => null,
Expand All @@ -76,6 +78,7 @@ public function __construct(
if ($this->metadata) {
$this->decodedMetadataErrorInfo = self::decodeMetadataErrorInfo($this->metadata);
}
$this->protobufErrors = $protobufErrors;
}

public function getStatus()
Expand Down Expand Up @@ -137,18 +140,29 @@ public function getErrorInfoMetadata()
return ($this->decodedMetadataErrorInfo) ? $this->decodedMetadataErrorInfo['errorInfoMetadata'] : null;
}

/**
* Returns the unserialized errors
* @return array
*/
public function getErrorDetails(): array
{
return $this->protobufErrors;
}

/**
* @param stdClass $status
* @return ApiException
*/
public static function createFromStdClass(stdClass $status)
{
$metadata = property_exists($status, 'metadata') ? $status->metadata : null;
$errors = [];
return self::create(
$status->details,
$status->code,
$metadata,
Serializer::decodeMetadata((array) $metadata)
Serializer::decodeMetadata((array) $metadata, $errors),
$errors,
);
}

Expand All @@ -165,11 +179,13 @@ public static function createFromApiResponse(
?array $metadata = null,
?Exception $previous = null
) {
$errors = [];
return self::create(
$basicMessage,
$rpcCode,
$metadata,
Serializer::decodeMetadata((array) $metadata),
Serializer::decodeMetadata((array) $metadata, $errors),
$errors,
$previous
);
}
Expand All @@ -194,6 +210,7 @@ public static function createFromRestApiResponse(
$rpcCode,
$metadata,
is_null($metadata) ? [] : $metadata,
self::decodeMetadataToProtobufErrors($metadata ?? []),
$previous
);
}
Expand Down Expand Up @@ -235,6 +252,7 @@ private static function containsErrorInfo(array $decodedMetadata)
* @param int $rpcCode
* @param iterable|null $metadata
* @param array $decodedMetadata
* @param array|null $protobufErrors
* @param Exception|null $previous
* @return ApiException
*/
Expand All @@ -243,6 +261,7 @@ private static function create(
int $rpcCode,
$metadata,
array $decodedMetadata,
?array $protobufErrors = null,
?Exception $previous = null
) {
$containsErrorInfo = self::containsErrorInfo($decodedMetadata);
Expand All @@ -263,11 +282,51 @@ private static function create(
$metadata = iterator_to_array($metadata);
}

return new ApiException($message, $rpcCode, $rpcStatus, [
'previous' => $previous,
'metadata' => $metadata,
'basicMessage' => $basicMessage,
]);
return new ApiException(
$message,
$rpcCode,
$rpcStatus,
[
'previous' => $previous,
'metadata' => $metadata,
'basicMessage' => $basicMessage,
],
$protobufErrors ?? []
);
}

/**
* Encodes decoded metadata to the Protobuf error type
*
* @param array $metadata
* @return array
*/
private static function decodeMetadataToProtobufErrors(array $metadata): array
{
$result = [];
Serializer::loadKnownMetadataTypes();

foreach ($metadata as $error) {
$message = null;

if (!isset($error['@type'])) {
continue;
}

$type = $error['@type'];

if (!isset(KnownTypes::JSON_TYPES[$type])) {
continue;
}

$class = KnownTypes::JSON_TYPES[$type];
$message = new $class();
$jsonMessage = json_encode(array_diff_key($error, ['@type' => true]));
$message->mergeFromJsonString($jsonMessage);
$result[] = $message;
}

return $result;
}

/**
Expand Down
66 changes: 66 additions & 0 deletions src/KnownTypes.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php
/*
* Copyright 2025 Google LLC
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
namespace Google\ApiCore;

class KnownTypes
{
public const GRPC_TYPES = [
'google.rpc.retryinfo-bin' => \Google\Rpc\RetryInfo::class,
'google.rpc.debuginfo-bin' => \Google\Rpc\DebugInfo::class,
'google.rpc.quotafailure-bin' => \Google\Rpc\QuotaFailure::class,
'google.rpc.badrequest-bin' => \Google\Rpc\BadRequest::class,
'google.rpc.requestinfo-bin' => \Google\Rpc\RequestInfo::class,
'google.rpc.resourceinfo-bin' => \Google\Rpc\ResourceInfo::class,
'google.rpc.errorinfo-bin' => \Google\Rpc\ErrorInfo::class,
'google.rpc.help-bin' => \Google\Rpc\Help::class,
'google.rpc.localizedmessage-bin' => \Google\Rpc\LocalizedMessage::class,
'google.rpc.preconditionfailure-bin' => \Google\Rpc\PreconditionFailure::class,
];

public const JSON_TYPES = [
'type.googleapis.com/google.rpc.RetryInfo' => \Google\Rpc\RetryInfo::class,
'type.googleapis.com/google.rpc.DebugInfo' => \Google\Rpc\DebugInfo::class,
'type.googleapis.com/google.rpc.QuotaFailure' => \Google\Rpc\QuotaFailure::class,
'type.googleapis.com/google.rpc.BadRequest' => \Google\Rpc\BadRequest::class,
'type.googleapis.com/google.rpc.RequestInfo' => \Google\Rpc\RequestInfo::class,
'type.googleapis.com/google.rpc.ResourceInfo' => \Google\Rpc\ResourceInfo::class,
'type.googleapis.com/google.rpc.ErrorInfo' => \Google\Rpc\ErrorInfo::class,
'type.googleapis.com/google.rpc.Help' => \Google\Rpc\Help::class,
'type.googleapis.com/google.rpc.LocalizedMessage' => \Google\Rpc\LocalizedMessage::class,
'type.googleapis.com/google.rpc.PreconditionFailure' => \Google\Rpc\PreconditionFailure::class,
];

public static function allKnownTypes(): array
{
return self::GRPC_TYPES + self::JSON_TYPES;
}
}
24 changes: 8 additions & 16 deletions src/Serializer.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,18 +53,6 @@ class Serializer
private static array $snakeCaseMap = [];
private static array $camelCaseMap = [];

private static $metadataKnownTypes = [
'google.rpc.retryinfo-bin' => \Google\Rpc\RetryInfo::class,
'google.rpc.debuginfo-bin' => \Google\Rpc\DebugInfo::class,
'google.rpc.quotafailure-bin' => \Google\Rpc\QuotaFailure::class,
'google.rpc.badrequest-bin' => \Google\Rpc\BadRequest::class,
'google.rpc.requestinfo-bin' => \Google\Rpc\RequestInfo::class,
'google.rpc.resourceinfo-bin' => \Google\Rpc\ResourceInfo::class,
'google.rpc.errorinfo-bin' => \Google\Rpc\ErrorInfo::class,
'google.rpc.help-bin' => \Google\Rpc\Help::class,
'google.rpc.localizedmessage-bin' => \Google\Rpc\LocalizedMessage::class,
];

private $fieldTransformers;
private $messageTypeTransformers;
private $decodeFieldTransformers;
Expand Down Expand Up @@ -178,9 +166,10 @@ public static function serializeToPhpArray(Message $message)
* Decode metadata received from gRPC status object
*
* @param array $metadata
* @param null|array $errors
* @return array
*/
public static function decodeMetadata(array $metadata)
public static function decodeMetadata(array $metadata, ?array &$errors = null)
{
if (count($metadata) == 0) {
return [];
Expand All @@ -192,13 +181,16 @@ public static function decodeMetadata(array $metadata)
'@type' => $key,
];
if (self::hasBinaryHeaderSuffix($key)) {
if (isset(self::$metadataKnownTypes[$key])) {
$class = self::$metadataKnownTypes[$key];
if (isset(KnownTypes::GRPC_TYPES[$key])) {
$class = KnownTypes::GRPC_TYPES[$key];
/** @var Message $message */
$message = new $class();
try {
$message->mergeFromString($value);
$decodedValue += self::serializeToPhpArray($message);
if (!is_null($errors)) {
$errors[] = $message;
}
} catch (\Exception $e) {
// We encountered an error trying to deserialize the data
$decodedValue += [
Expand Down Expand Up @@ -516,7 +508,7 @@ private static function getPhpArraySerializer()

public static function loadKnownMetadataTypes()
{
foreach (self::$metadataKnownTypes as $key => $class) {
foreach (KnownTypes::GRPC_TYPES as $key => $class) {
new $class();
}
}
Expand Down
Loading