我正在编写一个服务类,它使用 Guzzle 封装对某些 api 端点的调用。
我最终用基本相同的 Guzzle 异常处理编写了这些方法,即:
class ServiceClass {
public function getMethod(){
try {
$response = $guzzleClient->get("some/url");
// some business logic
return $data;
}
catch(ClientException $e) {
// handle exception
}
catch(RequestException $e) {
// handle exception
}
}
public function postMethod(){
try {
$response = $guzzleClient->post("another/url", [/* some data */]);
// other business logic
return;
}
catch(ClientException $e) {
// handle exception
}
catch(RequestException $e) {
// handle exception
}
}
}
由于每个端点的行为都是相同的,尽管是 POST 或 GET,也就是说,如果出现错误,它们会返回完全相同的响应主体结构(例如错误数组),我想知道是否有一种方法可以“扩展”每个方法重用相同的
try-catch
逻辑并隔离相关的单独业务逻辑。
我建议将异常的处理分离到服务的不同部分,例如:
class ServiceClass
{
public function getMethod()
{
try {
$response = $guzzleClient->get("some/url");
// some business logic
return $data;
} catch (\Exception $e) {
$this->handleException($e);
}
}
public function postMethod()
{
try {
$response = $guzzleClient->post("another/url", [/* some data */]);
// other business logic
return;
} catch (\Exception $e) {
$this->handleException($e);
}
}
protected function handleException(\Exception $e)
{
switch ($e) {
case $e instanceof RequestException::class:
// handle exception
break;
case $e instanceof ClientException::class:
// handle exception
break;
default:
throw $e;
}
}
}
如果您需要在多个类中执行此操作,则特征会很有用:
// ExceptionHandlerTrait.php
trait ExceptionHandlerTrait
{
protected function handleException(\Exception $e)
{
switch ($e) {
case $e instanceof RequestException::class:
// handle exception
break;
case $e instanceof ClientException::class:
// handle exception
break;
default:
throw $e;
}
}
}
// ServiceClass.php
class ServiceClass
{
use ExceptionHandlerTrait;
public function getMethod()
{
try {
$response = $guzzleClient->get("some/url");
// some business logic
return $data;
} catch (\Exception $e) {
$this->handleException($e);
}
}
public function postMethod()
{
try {
$response = $guzzleClient->post("another/url", [/* some data */]);
// other business logic
return;
} catch (\Exception $e) {
$this->handleException($e);
}
}
}
这只是一种解决方案。
如果您使用像 Symfony 这样的框架,您可以定义 Global ExceptionHandler 来对每个异常做出反应,而无需在每个文件中执行它(您可以信任它,并且不必每次都捕获它们。