Skip to content

Commit

Permalink
Simplify the wrapping of API exceptions
Browse files Browse the repository at this point in the history
  • Loading branch information
jeromegamez committed Jan 12, 2018
1 parent 6808ed9 commit e5fa43a
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 23 deletions.
34 changes: 19 additions & 15 deletions src/Firebase/Exception/ApiException.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,29 +22,16 @@ class ApiException extends \RuntimeException implements FirebaseException

public static function wrapThrowable(\Throwable $e): self
{
if ($e instanceof self) {
return $e;
}

if (!($e instanceof RequestException)) {
return new self($e->getMessage(), $e->getCode(), $e);
}

$request = $e->getRequest();
$response = $e->getResponse();
$message = $e->getMessage();
$message = self::getPreciseMessage($response) ?: $e->getMessage();
$code = $e->getCode();

if (\in_array($code, [StatusCode::STATUS_UNAUTHORIZED, StatusCode::STATUS_FORBIDDEN], true)) {
$class = PermissionDenied::class;
} else {
$class = static::class;
}

if ($response && JSON::isValid($responseBody = (string) $response->getBody())) {
$json = JSON::decode($responseBody, true);
$message = $json['error'] ?? $message;
}
$class = self::getTargetClassFromStatusCode($code);

$instance = new $class($message, $code, $e);
$instance->request = $request;
Expand All @@ -65,4 +52,21 @@ public function getResponse()
{
return $this->response;
}

private static function getTargetClassFromStatusCode($code): string
{
if (\in_array($code, [StatusCode::STATUS_UNAUTHORIZED, StatusCode::STATUS_FORBIDDEN], true)) {
return PermissionDenied::class;
}

return static::class;
}

private static function getPreciseMessage(ResponseInterface $response = null)
{
if ($response && JSON::isValid($responseBody = (string) $response->getBody())) {
$json = JSON::decode($responseBody, true);
return $json['error'] ?? null;
}
}
}
8 changes: 0 additions & 8 deletions tests/Firebase/Unit/Exception/ApiExceptionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,6 @@

class ApiExceptionTest extends UnitTestCase
{
public function testWrapApiException()
{
$source = new ApiException('Foo');
$result = ApiException::wrapThrowable($source);

$this->assertSame($source, $result);
}

public function testWrapClientException()
{
$source = new ClientException(
Expand Down

0 comments on commit e5fa43a

Please sign in to comment.