2016-07-04 58 views
0

我正在尝试自定义错误消息。 处理错误,我用 “的try/catch” 块根据this Recurly文档,像这样的例子:反复PHP客户端。如何自定义错误消息?

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. 
} 

但引用代码( )方法对于所有可能的错误总是返回零。

我对Recurly小组(或谁那里这个主题)问题: 我如何得到错误的错误代码?或者请解释我如何解决这个问题。谢谢!

回答

1

如果您看看Github上的PHP客户端,并且您搜索“throw new”,这是抛出异常时所做的事情,您会看到它们不会将异常错误代码设置为第二个参数异常构造方法。

在Github上

Recurly PHP客户: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'; 
} 
捕捉多个异常

OR

看看例外信息并比较它

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. 
}