PHP Avoid to repeat the same try catch(PHP避免重复使用相同的try catch)

120 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

如果你的代码中需要频繁使用try-catch包括代码,且异常处理方式都相同,记录日志并抛出一个友好的错误提示,那么可以使用下面的方式进行改进。

原代码:

try {
  // Use Stripe's library to make requests...
} catch(\Stripe\Error\Card $e) {
  // Since it's a decline, \Stripe\Error\Card will be caught
  $body = $e->getJsonBody();
  $err  = $body['error'];

  print('Status is:' . $e->getHttpStatus() . "\n");
  print('Type is:' . $err['type'] . "\n");
  print('Code is:' . $err['code'] . "\n");
  // param is '' in this case
  print('Param is:' . $err['param'] . "\n");
  print('Message is:' . $err['message'] . "\n");
} catch (\Stripe\Error\RateLimit $e) {
  // Too many requests made to the API too quickly
} catch (\Stripe\Error\InvalidRequest $e) {
  // Invalid parameters were supplied to Stripe's API
} catch (\Stripe\Error\Authentication $e) {
  // Authentication with Stripe's API failed
  // (maybe you changed API keys recently)
} catch (\Stripe\Error\ApiConnection $e) {
  // Network communication with Stripe failed
} catch (\Stripe\Error\Base $e) {
  // Display a very generic error to the user, and maybe send
  // yourself an email
} catch (Exception $e) {
  // Something else happened, completely unrelated to Stripe
}

改进之后:

function stripeResponse($function) {
    try {
      // Use Stripe's library to make requests...
      \Stripe\Stripe::setApiKey("my_key");
      $function();
    } catch(\Stripe\Error\Card $e) {
      // Since it's a decline, \Stripe\Error\Card will be caught
    } catch (\Stripe\Error\RateLimit $e) {
      // Too many requests made to the API too quickly
    } catch (\Stripe\Error\InvalidRequest $e) {
      // Invalid parameters were supplied to Stripe's API
    } catch (\Stripe\Error\Authentication $e) {
      // Authentication with Stripe's API failed
      // (maybe you changed API keys recently)
    } catch (\Stripe\Error\ApiConnection $e) {
      // Network communication with Stripe failed
    } catch (\Stripe\Error\Base $e) {
      // Display a very generic error to the user, and maybe send
      // yourself an email
    } catch (Exception $e) {
      // Something else happened, completely unrelated to Stripe
    }
}

return $this->stripeResponse(function() {
    \Stripe\Charge::create([
        "amount" => 100,
        "currency" => "eur",
        "source" => "token",
        "description" => "Description"
    ]);
});

//如果你想传入外部参数:
$a = [];
return $this->stripeResponse(function() use ($a) {
    \Stripe\Charge::create([
        "amount" => 100,
        "currency" => "eur",
        "source" => "token",
        "description" => "Description"
    ]);
});

//如果你想传入外部参数,同时还需要改变外部参数的值,可以使用引用&
$a = [];
return $this->stripeResponse(function() use (&$a) {
    \Stripe\Charge::create([
        "amount" => 100,
        "currency" => "eur",
        "source" => "token",
        "description" => "Description"
    ]);
});

Reference

写在最后

欢迎大家关注鄙人的公众号【麦田里的守望者zhg】,让我们一起成长,谢谢。 微信公众号个人博客