|
2 | 2 |
|
3 | 3 | namespace CodeOfDigital\LaravelUrlShortener\Drivers; |
4 | 4 |
|
| 5 | +use CodeOfDigital\LaravelUrlShortener\Exceptions\BadRequestException; |
| 6 | +use CodeOfDigital\LaravelUrlShortener\Exceptions\InvalidApiTokenException; |
| 7 | +use CodeOfDigital\LaravelUrlShortener\Exceptions\InvalidDataException; |
| 8 | +use CodeOfDigital\LaravelUrlShortener\Exceptions\InvalidResponseException; |
| 9 | +use CodeOfDigital\LaravelUrlShortener\Exceptions\MethodNotAllowedException; |
5 | 10 | use GuzzleHttp\ClientInterface; |
| 11 | +use GuzzleHttp\Exception\RequestException; |
6 | 12 | use GuzzleHttp\Psr7\Request; |
7 | 13 | use Illuminate\Support\Arr; |
8 | 14 | use Psr\Http\Message\ResponseInterface; |
@@ -37,8 +43,24 @@ public function shortenAsync($url, array $options = []) |
37 | 43 | $options = array_merge_recursive(Arr::add($this->object, 'json.url', $url), ['json' => $options]); |
38 | 44 | $request = new Request('POST', '/create'); |
39 | 45 |
|
40 | | - return $this->client->sendAsync($request, $options)->then(function (ResponseInterface $response) { |
41 | | - return str_replace('http://', 'https://', json_decode($response->getBody()->getContents())->data->tiny_url); |
42 | | - }); |
| 46 | + return $this->client->sendAsync($request, $options)->then( |
| 47 | + function (ResponseInterface $response) { |
| 48 | + return str_replace('http://', 'https://', json_decode($response->getBody()->getContents())->data->tiny_url); |
| 49 | + }, |
| 50 | + function (RequestException $e) { |
| 51 | + $this->getErrorMessage($e->getCode(), $e->getMessage()); |
| 52 | + } |
| 53 | + ); |
| 54 | + } |
| 55 | + |
| 56 | + protected function getErrorMessage($code, $message = null) |
| 57 | + { |
| 58 | + switch ($code) { |
| 59 | + case 400: throw new BadRequestException($message); |
| 60 | + case 401: throw new InvalidApiTokenException($message); |
| 61 | + case 405: throw new MethodNotAllowedException($message); |
| 62 | + case 422: throw new InvalidDataException($message); |
| 63 | + default: throw new InvalidResponseException($message); |
| 64 | + } |
43 | 65 | } |
44 | 66 | } |
0 commit comments