php - Symfony - 无法运行我的 createNotFoundException
问题描述
我创建了实体产品,当我想使用函数getProduct
或deleteProduct
产品在数据库中不存在时,我不能抛出异常。
我的代码:
/**
* @Route("/product/{product}", name="get_product", methods={"GET"})
*/
public function getProduct(Product $product)
{
if(!$product){
throw $this->createNotFoundException('Product not found');
}
return JsonResponse::create(['id' => $product->getId(), "name" => $product->getName(), "price" => $product->getPrice(), "description" => $product->getDescription()]);
}
/**
* @Route("/product/{product}", name="delete_product", methods={"DELETE"})
*/
public function deleteProduct(Product $product)
{
if(!$product){
throw $this->createNotFoundException('Product not found');
}
$this->em->remove($product);
$this->em->flush();
return JsonResponse::create('deleted');
}
解决方案
类型提示已经期望一个Product
对象。
public function deleteProduct(Product $product)
{
// $product is never null
dump($product->getName());
上面的代码和下面的一样
public function deleteProduct($productId)
{
$product = $this->getDoctrine()->getRepository(Product::class)
->find($productId);
// $product could be null
if(!$product){
throw $this->createNotFoundException('Product not found');
}
// $product is never null
dump($product->getName());
因为当对象不匹配时 Symfony paramTransformer 会抛出 NotFoundException。有关更多深入信息,请参阅文档
推荐阅读
- html - CSS - 无论视口大小如何,如何保持完整图像可见?
- python - 工作好几个小时后突然出现错误:调用 Python 对象时超出最大递归深度的递归错误
- android - obj\Debug\90\MonoAndroid,Version=v9.0.AssemblyAttributes.cs 在“Sources”参数中指定了多次
- c# - 为什么“System.Net.WebException:'底层连接已关闭:发送时发生意外错误。” 出现错误?
- python - 为什么我的 python 代码认为这个字符比另一个大?
- nginx - 如何配置 NGINX 和 uwsgi 以通过一个应用程序支持多个 TLD
- kubernetes - 为什么我的 Kubernates 集群上的入口在使用 nginx-ingress-controller 的指定主机上没有响应?
- c# - 如何将变量插入到 html 字符串中,确保它没有被插入到使用 c# 的元素中
- node.js - 在节点 js 中访问谷歌云秘密管理器数据以进行数据库连接
- python - 根据像素数分屏