Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 Controller won't catch exception

This is the route handler for my delete action. It works well as long as the item does not have any associations.

public function projectDeleteAction()
{
    try {
        $request = $this->get('request');
        $my_id = $request->query->get('id');

        $em = $this->get('doctrine.orm.entity_manager');

        $item = $em->find('MyBundle:Main', $my_id);

        $em->remove($item);
        $em->flush();

        $info = $item->getName();
        $result = 0;
    }
    catch (Exception $e) {
        $info = toString($e);
        $result = -1;
    }

    return $this->render('MyBundle:Main:response.xml.twig',
            array('info' => $info, 'result' => $result ));
}

I have already solved the error of trying to delete an item with associations, but through this process, the "flush" was throwing PDOException. I tried various ways to catch it, but it appears to be getting caught inside Symfony2 and then it responds with a HTTP 500 error. Is there a way that I can have Symfony2 not catch this so that I can handle it? This is an XML response using AJAX and so I would rather just send an error code per above.

like image 999
sleeves Avatar asked Apr 16 '11 20:04

sleeves


2 Answers

Try to change Exception\Exception if you didn't specified PDOException as Exception in a use statement. PHP tries to find \YourNamespaceWithController\Exception instead of \Exception (and it does not check the existence of such exception).

like image 197
Josef Cech Avatar answered Oct 03 '22 23:10

Josef Cech


It is better to catch the exception you really want to catch. In this example that is probably Doctrine/DBAL/DBALException and/or Doctrine/DBA/DBAException.

Thus

catch (Doctrine\DBAL\DBALException $e) {
  $result = -1;
};

I would recomment doing something like:

    } catch (\Exception $e) {
        switch (get_class($e)) {
            case 'Doctrine\DBAL\DBALException':
                echo "DBAL Exception<br />";
                break;
            case 'Doctrine\DBA\DBAException':
                echo "DBA Exception<br />";
                break;
            default:
                throw $e;
                break;
        }
    }

This actually catches the DB exceptions, and if for some reason some other exception occures, this is rethrown back into Symfony2.

like image 42
Rudy Broersma Avatar answered Oct 04 '22 01:10

Rudy Broersma