【问题标题】:Stop on any error and return the Json response停止任何错误并返回 Json 响应
【发布时间】:2014-11-28 23:45:12
【问题描述】:

我有这段代码,我想问哪种方法是停止代码执行的最佳方法,如果有任何失败,直接通过响应。看看这个:

public function guardarPaso6Action(Request $request)
{
    $em                  = $this->getDoctrine()->getManager();
    $session             = $request->getSession();
    $response['success'] = false;
    $status              = null;

    if ($request->isXmlHttpRequest()) {
        $productoSolicitud = $session->get('productoSolicitudId');
        $productoSolicitudEntity = $em->getRepository("AppBundle:ProductoSolicitud")->find($productoSolicitud);

        if (! $productoSolicitud) {
            $status = 400;
            $response['error'] = $this->get('translator')->trans('mensajes.msgElementoNoEncontrado', array('%pronombre%' => 'la','%elemento%' => 'solicitud de producto'), 'AppBundle');
        }

        $fabricanteEntity = new Entity\FabricanteDistribuidor();
        $fabricanteForm = $this->createForm(new Form\FabricanteForm(), $fabricanteEntity);
        $fabricanteForm->handleRequest($request);

        if ($fabricanteForm->isValid()) {
            try {
                $em->persist($fabricanteEntity);
                $em->flush();
                $session->set('fabricanteEntityId', $fabricanteEntity->getId());
            } catch (\Exception $ex) {
                $status = 400;
                $response['error'] = $ex->getMessage();
            }

            // Some code goes here

            $dataResponse['paises'] = $nombresPaises;
            $response['entities'] = $dataResponse;
            $response['success'] = true;
        } else {
            $status = 400;
            $response['error'] = $this->getFormErrors($fabricanteForm);
        }
    }

    return new JsonResponse($response, $status ?: 200);
}

在这种情况下:

  • 如果!$productoSolicitud 应该停止代码执行并通过JsonResponse
  • 如果有任何catch (\Exception $ex) 应该停止代码执行并通过JsonResponse

你有什么大主意吗?只需在出错时停止代码执行并通过return 语句。我如何做到这一点?我不确定使用exitbreak 是否可以完成这项工作,但我仍然有疑问,有什么建议吗?

【问题讨论】:

    标签: php algorithm symfony logic php-5.5


    【解决方案1】:

    当你想停止执行时,只需返回响应:

        public function guardarPaso6Action(Request $request)
        {
            $em                  = $this->getDoctrine()->getManager();
            $session             = $request->getSession();
            $response['success'] = false;
            $status              = 400;
    
            if ($request->isXmlHttpRequest()) {
                $productoSolicitud = $session->get('productoSolicitudId');
                $productoSolicitudEntity = $em->getRepository("AppBundle:ProductoSolicitud")->find($productoSolicitud);
    
                if (! $productoSolicitud) {
                    $response['error'] = $this->get('translator')->trans('mensajes.msgElementoNoEncontrado', array('%pronombre%' => 'la','%elemento%' => 'solicitud de producto'), 'AppBundle');
    
                    return new JsonResponse($response, $status);
                }
    
                $fabricanteEntity = new Entity\FabricanteDistribuidor();
                $fabricanteForm = $this->createForm(new Form\FabricanteForm(), $fabricanteEntity);
                $fabricanteForm->handleRequest($request);
    
                if ($fabricanteForm->isValid()) {
                    try {
                        $em->persist($fabricanteEntity);
                        $em->flush();
                        $session->set('fabricanteEntityId', $fabricanteEntity->getId());
                    } catch (\Exception $ex) {
                        $response['error'] = $ex->getMessage();
    
                        return new JsonResponse($response, $status);
                    }
    
                    // Some code goes here
    
                    $dataResponse['paises'] = $nombresPaises;
                    $response['entities'] = $dataResponse;
                    $response['success'] = true;
                    $status = 200;
                } else {
                    $response['error'] = $this->getFormErrors($fabricanteForm);
                }
            }
    
            return new JsonResponse($response, $status);
        }
    

    【讨论】:

      【解决方案2】:

      最简单的解决方案是抛出异常而不是使用 if-else 并使用 try-catch 包围所有内容。 像这样:

      try
        {
         if ($request->isXmlHttpRequest())
         {
              $productoSolicitud = $session->get('productoSolicitudId');
              $productoSolicitudEntity = $em->getRepository("AppBundle:ProductoSolicitud")->find($productoSolicitud);
      
              if (! $productoSolicitud) throw new \Exception ( $this->get('translator')->trans('mensajes.msgElementoNoEncontrado', array('%pronombre%' => 'la','%elemento%' => 'solicitud de producto'), 'AppBundle') );
      
              $fabricanteEntity = new Entity\FabricanteDistribuidor();
              $fabricanteForm = $this->createForm(new Form\FabricanteForm(), $fabricanteEntity);
              $fabricanteForm->handleRequest($request);
      
              if (!$fabricanteForm->isValid())   throw new \Exception ( json_encode( $this->getFormErrors($fabricanteForm) ));
      
              $em->persist($fabricanteEntity);
              $em->flush();
              $session->set('fabricanteEntityId', $fabricanteEntity->getId());
      
      
              // Some code goes here
      
              $dataResponse['paises'] = $nombresPaises;
              $response['entities'] = $dataResponse;
              $response['success'] = true;
          }
        }
        catch (\Exception $ex)
        {
            $status = 400;
            $response['error'] = $ex->getMessage();
        }
        return new JsonResponse($response, $status ?: 200);
      

      当使用 symfony 控制器时,你不应该终止 php 脚本本身(就像 exit 一样),而总是通过返回一个有效的响应来优雅地结束,这样任何下游组件仍然会被调用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-08-05
        • 2022-11-23
        • 1970-01-01
        • 2011-06-22
        • 1970-01-01
        • 1970-01-01
        • 2019-05-26
        • 2014-12-09
        相关资源
        最近更新 更多