首页 > 解决方案 > Symfony 4:捕获异常

问题描述

我试图捕捉错误但它不起作用,我总是看到 Symfony 异常页面,你在我的代码中看到任何错误吗?提前致谢。

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

这是错误 在此处输入图像描述 感谢安德里亚

标签: phpsymfony

解决方案


尽管您没有显示引发异常的行,但看起来您没有使用正确的命名空间:DoctrineDBALException是命名空间的,并且\DBALException在 Symfony 4 中不存在。

你可能想要:

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

要不就:

catch (DBALException $e) {

如果您use \Doctrine\DBAL\DBALException;在班级顶部有一个声明。

编辑:您显示的错误不是异常而是错误。您应该修复它以使其不会发生,但如果您想捕获它,您可以像捕获异常一样执行此操作:

catch (\Error $e) {

或者:

catch (\TypeError $e) {

推荐阅读