php - 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;
}
解决方案
尽管您没有显示引发异常的行,但看起来您没有使用正确的命名空间:DoctrineDBALException
是命名空间的,并且\DBALException
在 Symfony 4 中不存在。
你可能想要:
catch (\Doctrine\DBAL\DBALException $e) {
要不就:
catch (DBALException $e) {
如果您use \Doctrine\DBAL\DBALException;
在班级顶部有一个声明。
编辑:您显示的错误不是异常而是错误。您应该修复它以使其不会发生,但如果您想捕获它,您可以像捕获异常一样执行此操作:
catch (\Error $e) {
或者:
catch (\TypeError $e) {
推荐阅读
- c++ - 如何在 Visual Studio 2017 中自定义折叠
- python - Twitter 搜索 API:Python 中的 HTTPError(req.full_url, code, msg, hdrs, fp)
- android - 打开布局并移动以下项目
- php - 通过数据库使用 Vue 和 Axios 进行实时更新
- python - 使用 pybind11 从 C++ 反序列化 Python 中的 protobuf 缓冲区
- terraform - azurerm_virtual_machine 没有属性 identity.0.principal_id
- sql - 检查 Tarantool 中是否存在 SQL 表
- sql - 分组和更改数据
- mongodb - RunMongoAggregation 不适用于 Apache Nifi。它继续运行但没有给出任何输出
- mysql - Clickhouse柱结构