Gelso77
Gelso77

Reputation: 1895

Symfony 4: catch exception

I am trying to catch errors but it doesn't work, I always see the Symfony Exception page,do you see any errors in my code? thanks in advance.

namespace App\Controller;
use App\Entity\Product;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\AcceptHeader;
use Doctrine\ORM\ORMException;
use Doctrine\DBAL\DBALException;


public function index() {
        $request = Request::createFromGlobals();
        $content = $request->getContent();        
        $prod = [];
        $response = null;
        try
        {
            //$product->setPrice($request -> request -> get('price'));
            ....            
        }                  
        catch(\DBALException $e){
            $errorMessage = $e->getMessage();
            $response = New Response();
            $response -> setContent($errorMessage);
            $response -> setStatusCode(Response::HTTP_BAD_REQUEST);
        }
        catch(Exception $e){
            $errorMessage = $e->getMessage();
            $response = New Response();
            $response -> setContent($errorMessage);
            $response -> setStatusCode(Response::HTTP_BAD_REQUEST);

        }

        $response->headers->set('Content-Type', 'application/json');
        return $response;             
}

and this is the errors enter image description here thanks Andrea

Upvotes: 1

Views: 6342

Answers (1)

jeroen
jeroen

Reputation: 91734

Although you are not showing the line that is throwing the exception, it looks like you are not using the correct namespace: The Doctrine DBALException is namespaced and \DBALException does not exist in Symfony 4.

You probably want:

 catch (\Doctrine\DBAL\DBALException $e) {

or just:

catch (DBALException $e) {

if you have a use \Doctrine\DBAL\DBALException; statement at the top of your class.

Edit: The error you have shown, is not an exception but an error. You should fix this so that it cannot occur, but if you want to catch it, you could do that just like you catch the exceptions:

catch (\Error $e) {

or:

catch (\TypeError $e) {

Upvotes: 2

Related Questions