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

2019-08-28 06:00发布

问题:

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?

回答1:

Pass a callable, which can be an anonymous functions, 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(...);
});