Skip to content

Commit be19af3

Browse files
authored
Merge pull request #23 from resendlabs/feat-errors
2 parents 362323c + a17d808 commit be19af3

File tree

2 files changed

+39
-4
lines changed

2 files changed

+39
-4
lines changed

src/Transporters/HttpTransporter.php

+27-4
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
use JsonException;
66
use Psr\Http\Client\ClientExceptionInterface;
77
use Psr\Http\Client\ClientInterface;
8+
use Psr\Http\Message\ResponseInterface;
89
use Resend\Contracts\Transporter;
910
use Resend\Exceptions\ErrorException;
1011
use Resend\Exceptions\TransporterException;
@@ -43,18 +44,40 @@ public function request(Payload $payload): array
4344
throw new TransporterException($clientException);
4445
}
4546

46-
$contents = (string) $response->getBody();
47+
$contents = $response->getBody()->getContents();
48+
49+
$this->throwIfJsonError($response, $contents);
4750

4851
try {
4952
$response = json_decode($contents, true, 512, JSON_THROW_ON_ERROR);
5053
} catch (JsonException $jsonException) {
5154
throw new UnserializableResponse($jsonException);
5255
}
5356

54-
if (isset($response['error'])) {
55-
throw new ErrorException($response['error']);
57+
return $response;
58+
}
59+
60+
/**
61+
* Throw an exception if there is a JSON error.
62+
*/
63+
protected function throwIfJsonError(ResponseInterface $response, string $contents): void
64+
{
65+
if ($response->getStatusCode() < 400) {
66+
return;
5667
}
5768

58-
return $response;
69+
try {
70+
$response = json_decode($contents, true, 512, JSON_THROW_ON_ERROR);
71+
72+
$errors = ['missing_required_fields', 'missing_required_field', 'missing_api_key', 'invalid_api_key', 'invalid_from_address', 'validation_error', 'not_found', 'method_not_allowed', 'invalid_scope', 'restricted_api_key', 'internal_server_error'];
73+
if (
74+
isset($response['error']) ||
75+
in_array($response['name'], $errors)
76+
) {
77+
throw new ErrorException($response['error'] ?? $response);
78+
}
79+
} catch (JsonException $jsonException) {
80+
throw new UnserializableResponse($jsonException);
81+
}
5982
}
6083
}

tests/Transporters/HttpTransporter.php

+12
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,18 @@
9595
$this->http->request($payload);
9696
})->throws(UnserializableResponse::class, 'Syntax error');
9797

98+
test('throw json errors', function () {
99+
$payload = Payload::create('email', ['to' => '[email protected]']);
100+
$response = new Response(422, [], 'err');
101+
102+
$this->client
103+
->shouldReceive('sendRequest')
104+
->once()
105+
->andReturn($response);
106+
107+
$this->http->request($payload);
108+
})->throws(UnserializableResponse::class, 'Syntax error');
109+
98110
test('request can handle server errors', function () {
99111
$payload = Payload::create('email', ['to' => '[email protected]']);
100112
$response = new Response(422, [], json_encode([

0 commit comments

Comments
 (0)