|
5 | 5 | use JsonException;
|
6 | 6 | use Psr\Http\Client\ClientExceptionInterface;
|
7 | 7 | use Psr\Http\Client\ClientInterface;
|
| 8 | +use Psr\Http\Message\ResponseInterface; |
8 | 9 | use Resend\Contracts\Transporter;
|
9 | 10 | use Resend\Exceptions\ErrorException;
|
10 | 11 | use Resend\Exceptions\TransporterException;
|
@@ -43,18 +44,40 @@ public function request(Payload $payload): array
|
43 | 44 | throw new TransporterException($clientException);
|
44 | 45 | }
|
45 | 46 |
|
46 |
| - $contents = (string) $response->getBody(); |
| 47 | + $contents = $response->getBody()->getContents(); |
| 48 | + |
| 49 | + $this->throwIfJsonError($response, $contents); |
47 | 50 |
|
48 | 51 | try {
|
49 | 52 | $response = json_decode($contents, true, 512, JSON_THROW_ON_ERROR);
|
50 | 53 | } catch (JsonException $jsonException) {
|
51 | 54 | throw new UnserializableResponse($jsonException);
|
52 | 55 | }
|
53 | 56 |
|
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; |
56 | 67 | }
|
57 | 68 |
|
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 | + } |
59 | 82 | }
|
60 | 83 | }
|
0 commit comments