Skip to content

Commit

Permalink
Propagate the Discord API response exceptions (#42)
Browse files Browse the repository at this point in the history
  • Loading branch information
jee7 authored Oct 13, 2020
1 parent 48e04ef commit 32d5714
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 7 deletions.
4 changes: 2 additions & 2 deletions src/Discord.php
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ protected function request($verb, $endpoint, array $data)
]);
} catch (RequestException $exception) {
if ($response = $exception->getResponse()) {
throw CouldNotSendNotification::serviceRespondedWithAnHttpError($response);
throw CouldNotSendNotification::serviceRespondedWithAnHttpError($response, $response->getStatusCode(), $exception);
}

throw CouldNotSendNotification::serviceCommunicationError($exception);
Expand All @@ -101,7 +101,7 @@ protected function request($verb, $endpoint, array $data)
$body = json_decode($response->getBody(), true);

if (Arr::get($body, 'code', 0) > 0) {
throw CouldNotSendNotification::serviceRespondedWithAnApiError($body);
throw CouldNotSendNotification::serviceRespondedWithAnApiError($body, $body['code']);
}

return $body;
Expand Down
13 changes: 8 additions & 5 deletions src/Exceptions/CouldNotSendNotification.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,28 +10,31 @@ class CouldNotSendNotification extends Exception
{
/**
* @param \Psr\Http\Message\ResponseInterface $response
* @param int $code
* @param \Exception $exception
*
* @return static
*/
public static function serviceRespondedWithAnHttpError(ResponseInterface $response)
public static function serviceRespondedWithAnHttpError(ResponseInterface $response, $code, $exception)
{
$message = "Discord responded with an HTTP error: {$response->getStatusCode()}";

if ($error = Arr::get(json_decode($response->getBody(), true), 'message')) {
$message .= ": $error";
}

return new static($message);
return new static($message, $code, $exception);
}

/**
* @param array $response
* @param int $code
*
* @return static
*/
public static function serviceRespondedWithAnApiError(array $response)
public static function serviceRespondedWithAnApiError(array $response, $code, $exception)
{
return new static("Discord responded with an API error: {$response['code']}: {$response['message']}");
return new static("Discord responded with an API error: {$response['code']}: {$response['message']}", $code);
}

/**
Expand All @@ -41,6 +44,6 @@ public static function serviceRespondedWithAnApiError(array $response)
*/
public static function serviceCommunicationError(Exception $exception)
{
return new static("Communication with Discord failed: {$exception->getCode()}: {$exception->getMessage()}");
return new static("Communication with Discord failed: {$exception->getCode()}: {$exception->getMessage()}", $exception->getCode(), $exception);
}
}

0 comments on commit 32d5714

Please sign in to comment.