Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Wrap a variable block in the same try-catch

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?

like image 801
gbalduzzi Avatar asked Dec 14 '18 10:12

gbalduzzi


People also ask

Should I wrap everything try catch?

No, it's actually a reasonable thing to do in some applications, so that you can detect, log, report, and potentially handle (but most likely just rethrow or terminate) exceptions that are not caught elsewhere in the code.

What code is intended to be wrapped in a try block?

The code that we imagine might be problematic, the call to Connect(), is now wrapped in a try block. Any exception that occurs in the code inside the catch block will immediately transfer to the code in the catch block, where we can specify what we want to happen if the call fails.

Can we use multiple try catch in PHP?

Multiple catch blocks can be used to catch different classes of exceptions. Normal execution (when no exception is thrown within the try block) will continue after that last catch block defined in sequence. Exceptions can be throw n (or re-thrown) within a catch block.


1 Answers

Pass a callable, which can be an anonymous function, a regular function, or a class method:

function executeGuzzle(callable $fun) {
    try {
        return $fun();
    } catch (ClientException $clientException) {
        // Do stuff
    } catch (ConnectException $connectException) {
        // Do stuff
    } catch (RequestException $requestException) {
        // Do stuff
    }
}

$res = executeGuzzle(function () use ($client) {
    return $client->get(...);
});
like image 153
deceze Avatar answered Sep 27 '22 19:09

deceze