首页 > 解决方案 > Symfony - 无法运行我的 createNotFoundException

问题描述

我创建了实体产品,当我想使用函数getProductdeleteProduct产品在数据库中不存在时,我不能抛出异常。

我的代码:

/**
 * @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');
}

标签: phpsymfonyexceptionthrow

解决方案


类型提示已经期望一个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。有关更多深入信息,请参阅文档


推荐阅读