Laravel良好实践与例外和尝试和捕获块

时间:2015-11-03 18:30:08

标签: performance laravel try-catch

我正在构建一个网络应用,客户可以在其中购买许多不同的计划,并且我使用Stripe API进行付款。当客户想要购买计划时,它必须填写信用卡详细信息和电子邮件。所以,我在 RegistrationController 中获取了所有这些表单数据。

问题是,我必须在post方法中做很多事情,如:

  • 检查所选计划是否存在(可能有人可能破解html表单源)。
  • 创建Stripe Costumer。
  • 为我已创建的客户创建条带订阅。
  • 创建新的Eloquent用户,同步所选的计划并将条带信息(条带ID等)添加到用户实例。

由于我必须执行许多步骤,因此我决定使用Try& 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等),以便在每个Catch中逻辑变大。
  • 记录事件。
  • 返回错误。

这是服务类管理Stripe客户的方法示例:

public function createNewStripeCustomer($request)
{
    $response = Customer::create(array(
        "description" => "Customer for test@example.com",
        "source" => $request->stripeToken,
        "email" => $request->email,
    ));

    if(true)
    {
        return $response;
    }

    throw new StripeCustomerNotCreated();
}

*如果出现任何错误,我会返回类似API的JSON。

*我有" variables.php"文件在/ Config目录中保存所有错误消息。

我试图在Handler.php文件中保存每个Exception的逻辑(使用开关循环),但它并没有像我期望的那样工作。其他选项是替换许多if& else或嵌套的try& catch块的try& catch块,但它仍然很混乱。

使这项工作有效的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

我终于在Handler.php中找到了处理Stripe Exceptions(不是我自定义的)的解决方案。我发现这个post可能对某人有所帮助。

相关问题