2015-11-03 41 views
1

我正在構建一個Web應用程序,客戶可以購買許多不同計劃,並且我正在使用Stripe API進行付款。當客戶想要購買計劃時,必須填寫信用卡詳情和電子郵件。所以,我在我的RegistrationController中獲得了所有這些表單數據。Laravel具有例外和嘗試與捕獲塊的良好實踐

的事情是,我必須做很多事情POST方法,如:

  • 檢查所選計劃的存在(也許有人可以砍的HTML格式的源)。
  • 創建條紋客戶。
  • 爲我創建的客戶創建條紋訂閱。
  • 創建新的Eloquent用戶,同步所選計劃並將條帶信息(條紋ID等)添加到用戶實例。

由於我必須做很多步驟,我決定用一個嘗試& Catch塊,並創建自定義的例外是,如果事情失敗,我將能夠跟蹤這些錯誤發生。問題是,我在這個RegistrationController凌亂的方法結束:

public function postRegistration(RegistrationRequest $request, 
           StripeCostumer $stripeCustomer, 
           StripeSubscription $stripeSubscription) 
{ 
    if ($request['training_plan']) 
    { 

     if (! $this->PlanExists($request['training_plan'])) 
     { 
      \Log::alert('Somebody tried to hack the plan: '. 
      $request['email']); 

      return response()->json(
       ['error' => \Config::get('variables.104')], 
       Response::HTTP_NOT_FOUND); 
     } 
    } 
    try 
    { 
     $response = $stripeCustomer->createNewStripeCostumer($request); 

     $plans = $stripeSubscription->createNewStripeSubscription($response->id, $request); 

     $user = $this->userRepo->create($request->all()); 

     $user->syncUserPlans($plans); 

     $this->userRepo->saveStripeInfo($user,$response); 

    } 
    catch(StripeCustomerNotCreated $e) 
    { 
     \Log::error('Couldn't create a new Stripe Costumer: '. 
      $request['email']); 

     return response()->json(
      ['error' => \Config::get('variables.106')], 
      Response::HTTP_PAYMENT_REQUIRED); 

    } 
    catch(StripeSubscriptionNotCreated $e) 
    ... 
    catch(EloquentUserNotCreated $e) 
    ... 
    catch(StripeInfoNotSaved $e) 
    ... 

    event(new UserRegistration($user)); 

    \Auth::login($user); 

    return redirect('/'); 
} 

我沒有寫每Catch塊(我現在有4-5),但每次我拋出一個異常,我必須:

  • 撤銷所有先前的操作(創建Stripe Customer,Eloquent User等),因此在每次捕捉中邏輯變得更大。
  • 記錄事件。
  • 返回錯誤。

這是一個服務類的方法來管理客戶條紋的例子:

public function createNewStripeCustomer($request) 
{ 
    $response = Customer::create(array(
     "description" => "Customer for [email protected]", 
     "source" => $request->stripeToken, 
     "email" => $request->email, 
    )); 

    if(true) 
    { 
     return $response; 
    } 

    throw new StripeCustomerNotCreated(); 
} 

*如果有任何錯誤,我回到像一個API一個JSON。

*我在/ Config目錄中的「variables.php」文件中保存了所有錯誤消息。

我試圖在Handler.php文件中保存每個異常的邏輯(使用開關循環),但它不起作用。其他選項是替換嘗試& catch塊的許多if &其他或嵌套嘗試& catch塊,但它仍然凌亂。

什麼應該是使這項工作有效的最佳方法?

回答

1

我終於在Handler.php中得到了一個處理Stripe Exceptions(不是我自定義的)的解決方案。我發現這post可能有助於某人。