2014-11-28 2 views
1

У меня есть этот код, и я спрашиваю, что это лучший способ остановить выполнение кода и перейти непосредственно через ответ, если какой-либо сбой. Посмотрите на это:Остановить любую ошибку и вернуть ответ Json

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. Как я это достигаю? Я не уверен, что если использование 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

Простейшим решением было бы исключение вместо использования 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 скрипт (например, с выходом) само по себе, но всегда в конечном грациозно, возвращая правильный ответ, так что любые компоненты вниз по течению еще дозвонились.

Смежные вопросы