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

前端 未结 1 322
春和景丽
春和景丽 2021-01-06 18:30

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:

相关标签:
1条回答
  • 2021-01-06 19:09

    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(...);
    });
    
    0 讨论(0)
提交回复
热议问题