2017-07-06 68 views
0

我從條紋API處理錯誤 - 一切使用的條紋文檔提供的標準try/catch塊正常工作:抽象的try/catch PHP - 條紋錯誤處理

try { 

    // Use Stripe's library to make requests... 

} catch(\Stripe\Error\Card $e) { 

    //card errors 

    $body = $e->getJsonBody(); 
    $err = $body['error']; 

    print('Status is:' . $e->getHttpStatus() . "\n"); 
    print('Type is:' . $err['type'] . "\n"); 
    print('Code is:' . $err['code'] . "\n"); 
    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 
} 

然而,這是一個很大的代碼,我發現自己重複它。我有點卡在如何把它整理起來。這樣的事情將是理想的:

try { 

    // Use Stripe's library to make requests... 

} // catch all errors in one line 

回答

0

有一個處理它爲您的函數:

function makeStripeApiCall($method, $args) { 
    try { 
     // call method 
    } catch (...) { 
     // handle error type 1 
    } catch (...) { 
     // handle error type 2 
    } ... 
} 

現在:

  1. 如何通過$method?有幾種方法可以做到這一點;例如:

    $method = 'charge'; 
    $this->stripe->{$method}($args); 
    
    $method = [$stripe, 'charge']; 
    call_user_func_array($method, $args); 
    

    $method = function() use ($stripe, $args) { return $stripe->charge($args); }; 
    $method(); 
    

    選擇最適合您的情況。

  2. 如何正確處理錯誤?

    您應該捕獲特定的Stripe異常並根據需要將它們轉換爲您自己的內部異常類型。有幾種廣泛類型的問題需要以不同的方式處理:

    1. 不良請求,例如,卡拒絕:您希望直接在調用業務邏輯代碼中捕獲這些錯誤,並根據特定問題執行某些操作

    2. 服務已關閉,例如, Stripe\Error\ApiConnection或速率限制:你不能做與那些除了稍後再試,你想不想找個上漲趕上這些錯誤,並用「對不起,稍後再試」消息

    3. 錯誤的配置呈現給用戶,例如Stripe\Error\Authentication:沒有什麼可以自動完成,你可以用一個500 HTTP服務器錯誤向用戶呈現,響警鐘,並獲得devop修復認證密鑰

    這些基本上是種異常類型你想內部定義,然後適當地捕捉它們。例如: -

    ... 
    catch (\Stripe\Error\ApiConnection $e) { 
        trigger_error($e->getMessage(), E_USER_WARNING); 
        throw new TransientError($e); 
    } 
    ... 
    

這一切後,你將減少API調用是這樣的:

try { 
    return makeStripeApiCall('charge', $args); 
} catch (BadRequestError $e) { 
    echo 'Card number invalid: ', $e->getMessage(); 
} 
// don't catch other kinds of exception here, 
// let a higher up caller worry about graver issues 
+0

感謝您的回答 - 這是非常有用的。我的主要問題是傳遞方法,因爲try塊會有很大的差異。它可能會收取費用,檢索客戶,創建訂閱,更改訂閱計劃,添加優惠券 - 所有這些都有不同的參數和元數據。 – Ryan

+0

一個匿名函數應該是最靈活的。 – deceze

+0

謝謝 - 我會研究一下 – Ryan