symfony2 and throwing exception error

前端 未结 3 352
太阳男子
太阳男子 2021-01-01 12:13

I am trying to throw exceptions and I am doing the following:

use Symfony\\Component\\HttpKernel\\Exception\\HttpNotFoundException;
use Symfony\\Component\\S         


        
相关标签:
3条回答
  • 2021-01-01 12:27

    In the controller, you can simply do:

    public function someAction()
    {
        // ...
    
        // Tested, and the user does not have permissions
        throw $this->createAccessDeniedException("You don't have access to this page!");
    
        // or tested and didn't found the product
        throw $this->createNotFoundException('The product does not exist');
    
        // ...
    }
    

    In this situation, there'se no need to include the use Symfony\Component\HttpKernel\Exception\HttpNotFoundException; at the top. The reason for that is that you're not using the class directly, like using the constructor.

    Outside the controller, you must indicate where the class can be found, and throw an exception as you would normally do. Like this:

    use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
    
    // ...
    
    // Something is missing
    throw new HttpNotFoundException('The product does not exist');
    

    or

    use Symfony\Component\Security\Core\Exception\AccessDeniedException;
    
    // ...
    
    // Permissions were denied
    throw new AccessDeniedException("You don't have access to this page!");
    
    0 讨论(0)
  • 2021-01-01 12:29

    Try:

    use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
    

    and

    throw new NotFoundHttpException("Page not found");
    

    I think you got it a bit backwards :-)

    0 讨论(0)
  • 2021-01-01 12:32

    If its in a controller, you can do it this way :

    throw $this->createNotFoundException('Unable to find entity.');
    
    0 讨论(0)
提交回复
热议问题