diff --git a/app/Exceptions/EmptyRajaOngkirAPIException.php b/app/Exceptions/EmptyRajaOngkirAPIException.php new file mode 100644 index 0000000..e6f022c --- /dev/null +++ b/app/Exceptions/EmptyRajaOngkirAPIException.php @@ -0,0 +1,12 @@ +apiKey = env('RAJAONGKIR_API_KEY'); + if(empty($this->apiKey)) throw new EmptyRajaOngkirAPIException(); + } + public function indexProvince() { $cacheKey = 'provinces'; @@ -17,19 +27,20 @@ public function indexProvince() $provinces = Cache::remember($cacheKey, $cacheTime, function () { try { $client = new Client(); + $response = $client->request('GET', 'https://api.rajaongkir.com/starter/province', [ 'headers' => [ - 'key' => env('RAJAONGKIR_API_KEY'), - 'content-type' => 'application/x-www-form-urlencoded' + 'key' => $this->apiKey, + 'content-type' => 'application/x-www-form-urlencoded', ], ]); $provinces = json_decode($response->getBody())->rajaongkir->results; } catch (GuzzleException $e) { - // Handle any exception from Guzzle - $provinces = [$e->getMessage()]; - } + Log::debug('Error: ' . json_encode($e->getMessage())); + $provinces = []; + } return $provinces; }); @@ -38,7 +49,7 @@ public function indexProvince() public function indexCity(Request $request, $id) { - $cacheKey = 'cities_' . $id; + $cacheKey = 'cities_'.$id; $cacheTime = 60 * 60 * 24; // Cache for 24 hours $cities = Cache::remember($cacheKey, $cacheTime, function () use ($id) { @@ -46,8 +57,8 @@ public function indexCity(Request $request, $id) $client = new Client(); $response = $client->request('GET', 'https://api.rajaongkir.com/starter/city', [ 'headers' => [ - 'key' => env('RAJAONGKIR_API_KEY'), - 'content-type' => 'application/x-www-form-urlencoded' + 'key' => $this->apiKey, + 'content-type' => 'application/x-www-form-urlencoded', ], 'query' => [ 'province' => $id, @@ -56,8 +67,9 @@ public function indexCity(Request $request, $id) $cities = json_decode($response->getBody())->rajaongkir->results; } catch (GuzzleException $e) { - // Handle any exception from Guzzle - $cities = [$e->getMessage()]; + Log::debug('Error: ' . json_encode($e->getMessage())); + + $cities = []; } return $cities;