2016-07-04 40 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. 
} 
相關問題