Search code examples
phpsymfonyexceptionthrow

Symfony - Can't thow my createNotFoundException in Action


I've created entity product and I can't throw exceptions when I want use function getProduct or deleteProduct and the product doesn't exists in database.

My code:

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

Solution

  • The type hinting already expect a Product object.

    public function deleteProduct(Product $product)
    {
        // $product is never null
        dump($product->getName());
    

    The code above is the same than below

    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());
    

    Because Symfony paramTransformer throw a NotFoundException when the object is not matched. see the doc for more in depth info