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

戏子无情 提交于 2019-12-08 06:35:25

问题


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(...);
});


来源:https://stackoverflow.com/questions/53777969/php-wrap-a-variable-block-in-the-same-try-catch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!