Php Symfony-Can';我的createNotFoundException正在运行吗
我已经创建了实体产品,当我想使用函数Php Symfony-Can';我的createNotFoundException正在运行吗,php,symfony,exception,throw,Php,Symfony,Exception,Throw,我已经创建了实体产品,当我想使用函数getProduct或deleteProduct并且产品在数据库中不存在时,我不能抛出异常 我的代码: /** * @Route("/product/{product}", name="get_product", methods={"GET"}) */ public function getProduct(Product $product) { if(!$product){ throw $this->createNotFoun
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');
}
暗示的类型已经期望一个
产品
对象
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。请参阅文档以获取更深入的信息类型提示已期望使用
产品
对象
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。查看文档以了解更深入的信息那么到底发生了什么?“我的车不开了”是不够的。是否有回应?它不进入if案例吗?我猜$product不是空的,也不是空的……它没有输入if,但它已经被解决了。那么到底发生了什么呢?“我的车不开了”是不够的。是否有回应?它不进入if案例吗?我猜$product不是空的或null的…它没有输入if案例,但它已经解决了。