PHP客户端.如何自定义错误消息


Recurly PHP client. How to customize error messages?

我正在尝试自定义错误消息。为了处理错误,我使用了"try/catch"根据这个Recurly文档,像这样:

try {
  $account = Recurly_Account::get('my_account_id');
  $subscription = new Recurly_Subscription();
  $subscription->account = $account;
  $subscription->plan_code = 'my_plan_code';
  $subscription->coupon_code = 'my_coupon_code';
  /* .. etc .. */
  $subscription->create();
}
catch (Exception $e) {
  $errorMsg = $e->getMessage();
  print $errorMsg;
}

我想在catch块中使用这样的代码:

catch (Exception $e) {
  $errorCode = $e->getCode();
  print $myErrorMsg[$errorCode]; // array of my custom messages.
}

但是getCode()方法对于所有可能的错误总是返回0。

我对Recurly团队的问题(或者这个主题中的人):我如何得到错误的错误代码?或者请告诉我如何解决这个话题。谢谢!

如果你在Github上查看PHP客户端并搜索"throw new",这是抛出异常时所做的事情,你会看到他们不设置异常错误代码异常构造函数方法的第二个参数。

PHP Client on Github: https://github.com/recurly/recurly-client-php/search?utf8=%E2%9C%93&q=throw+new

PHP异常文档: http://php.net/manual/en/language.exceptions.extending.php

因此,您需要根据它们的名称捕获更多的异常例如

catch (Recurly_NotFoundError $e) {
  print 'Record could not be found';
}

查看异常消息并比较

catch (Exception $e) {
  $errorMessage = $e->getMessage();
  if($errorMessage=='Coupon is not redeemable.')
  {
    $myerrorCode=1;
  }
  //Add more else if, or case switch statement to handle the various errors you want to handle
  print $myErrorMsg[$myerrorCode]; // array of my custom messages.
}