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

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

报告相同问题?

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据