Skip to content

Commit

Permalink
refactor: parse exception to 'BrasilApiException' independent of API …
Browse files Browse the repository at this point in the history
…return
  • Loading branch information
andreoneres committed Mar 9, 2023
1 parent 7a818a5 commit 28d9a62
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 7 deletions.
21 changes: 20 additions & 1 deletion src/Exceptions/BrasilApiException.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,20 @@ class BrasilApiException extends Exception
*/
private array $errors;

public function __construct(string $message = "", int $code = 0, array $errors = [])
/**
* The raw response returned by BrasilApi
*/
private string $rawResponse;

public function __construct(
string $message = "",
int $code = 0,
array $errors = [],
string $rawResponse = ""
)
{
$this->errors = $errors;
$this->rawResponse = $rawResponse;
parent::__construct($message, $code);
}

Expand All @@ -26,4 +37,12 @@ public function getErrors(): array
{
return $this->errors;
}

/**
* Returns the raw response returned by BrasilApi
*/
public function getRawResponse(): string
{
return $this->rawResponse;
}
}
12 changes: 6 additions & 6 deletions src/Handlers/ResponseHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,13 @@ public static function failure(RequestException $exception): void
}

/**
* Parse a GuzzleHttp\Exception\RequestException into a BrasilApiException,
* if possible depending on the response body.
* Parse a GuzzleHttp\Exception\RequestException into a BrasilApiException.
*
* @param RequestException $exception The exception to be parsed
*
* @return BrasilApiException|RequestException
* @return BrasilApiException
*/
private static function parseException(RequestException $exception): BrasilApiException|RequestException
private static function parseException(RequestException $exception): BrasilApiException
{
$response = $exception->getResponse();

Expand All @@ -56,13 +55,14 @@ private static function parseException(RequestException $exception): BrasilApiEx
try {
$error = self::toArray($body);
} catch (InvalidJsonException) {
return $exception;
$error = [];
}

return new BrasilApiException(
$error["message"] ?? "An error occurred",
$response->getStatusCode(),
$error["errors"] ?? []
$error["errors"] ?? [],
$body
);
}

Expand Down

0 comments on commit 28d9a62

Please sign in to comment.