Hi Folks, have you encountered an ugly Exception when making a post, get, put, delete to external API when an error like 500 or 404 occurs. Today you are at the right place, after reading this you will be able to show a nice message to your users in case of any of those errors occurs
When making a request to external API using guzzle to solve this problem you will need to catch the Exception by following the steps below.
- Prepare your request using Guzzle, I believe you know or have set it up already
- Make a post or get request to your external API
public function create(Request $request) {
$input = $request->all();
try {
$client = new Client();
$headers = ['API-Key' => env('API_KEY')];
$url = 'api/post/create';
$response = $client->request('POST', $url, ['headers' => $headers, 'query' => $input]);
$res = json_decode($response->getBody());
//here will catch error to aviod ugly message to users
} catch (\GuzzleHttp\Exception\RequestException $res) {
if ($res->hasResponse()) {
$response = $res->getResponse();
if ($response->getStatusCode() == 500) {
abort(500);
} if ($response->getStatusCode() == 404) {
abort(404);
}
}
}
}
Congrats , you have saved your users from seeing that ugly message . Share and comment
Continue Reading
Be first to comment