PHP-在同一try-catch中包装变量块 [英] PHP - Wrap a variable block in the same try-catch
问题描述
在我的PHP项目中,我使用Guzzle发出许多不同的API请求。为了处理所有异常,每个API调用都包装在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
}
对于每个请求,exceptiuon处理是相同的,但是实际的执行块相差很多,并且不能简单地由一系列选项来描述。
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.
有没有一种方法可以创建功能/类将定制执行块包装到相同的try-catch处理中?
Is there a way to create a function/class able to wrap a custom execution block into the same try-catch handling?
我想到的唯一选择是使用带有函数的接口每个孩子扩展的execution()
和具有try-catch块并仅调用 run()
在执行块中> $ this-> execution()。可以,但是我发现为每个仅在项目的一点使用的不同API调用创建一个全新的类太冗长。
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?
推荐答案
传递可调用对象,可以是匿名函数,常规函数或类方法:
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(...);
});
这篇关于PHP-在同一try-catch中包装变量块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!