2014-11-28 2 views
1

이 코드가 있는데 코드 실행을 중지하고 실패하면 직접 물마루 응답으로 이동하는 가장 좋은 방법은 무엇입니까? 코드 실행을 중지하고 catch (\Exception $ex) 코드의 실행을 중지해야하는 경우 JsonResponse 오류가 발생하면 중지하고 Json 응답을 반환하십시오.

  • 을 거친 JsonResponse
  • 통과해야

    • 만약 !$productoSolicitud 경우 :이 경우

      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); 
      } 
      

      하십시오 이것 봐

    큰 아이디어를 얻었습니까? 오류가 발생하면 코드 실행을 중지하고 return 문을 사용합니다. 나는 이것을 어떻게 얻는가? exit 또는 break을 사용하면 나에게 의심의 여지가 있지만이 문제에 대한 조언이 있는지 확실하지 않습니다.

    답변

    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); 
        } 
    
    0

    쉬운 솔루션을 사용하는 대신 예외를 던질 경우 - 다른 시도 - 캐치 모든 suround하는 것입니다. 이처럼 는 : 심포니 컨트롤러를 사용하는 경우

    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); 
    

    , 당신은 그 자체 (출구와 같은) PHP 스크립트를 종료 없지만, 항상 다운 스트림 구성 요소가 여전히 전화를받을 수 있도록 유효한 응답을 반환하여 정상적으로 종료 안됩니다.

    관련 문제