in my PHP project, I use Guzzle to make a lot of different API requests. In order to handle all exception, each API call is wrapped into a try-catch block. An example:
try {
$res = $client->get($url, [
'headers' => [
'Authorization' => "bearer " . $jwt,
]
]);
} catch (ClientException $clientException) {
// Do stuff
} catch (ConnectException $connectException) {
// Do stuff
}catch (RequestException $requestException){
// Do stuff
}
For each request, the exceptiuon handling is the same but the actual execution block differs a lot and can not be simply described by an array of options.
Is there a way to create a function/class able to wrap a custom execution block into the same try-catch handling?
The only options I came up with is to use an interface with a function execution()
that is extended by each child and a function run()
that has the try-catch blocks and simply calls $this->execution()
inside the execution block. It would work, but I found too verbose the creation of a whole new class for each different API call that is only used in one point of my project.
Is there a better/less verbose solution to avoid code repetition of the same exception handling?