doude5860 2019-04-29 12:40
浏览 67
已采纳

Symfony 4:捕获异常

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

  • 写回答

1条回答 默认 最新

  • doutan1637 2019-04-29 12:54
    关注

    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) {
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大