Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/symfony/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Symfony2模拟404错误?_Symfony_Symfony 2.1 - Fatal编程技术网

如何使用Symfony2模拟404错误?

如何使用Symfony2模拟404错误?,symfony,symfony-2.1,Symfony,Symfony 2.1,因此,我正在寻找一种模拟404错误的方法,我尝试了以下方法: throw $this->createNotFoundException(); 还有这个 return new Response("",404); 但没有一个能起作用 您可以在Symfony2文档中找到解决方案: 管理错误和404页 public function indexAction() { // retrieve the object from database $product = ...;

因此,我正在寻找一种模拟404错误的方法,我尝试了以下方法:

throw $this->createNotFoundException();  
还有这个

return new Response("",404);

但没有一个能起作用

您可以在Symfony2文档中找到解决方案:

管理错误和404页

public function indexAction()
{
    // retrieve the object from database
    $product = ...;
    if (!$product) {
        throw $this->createNotFoundException('The product does not exist');
    }

    return $this->render(...);
}
文档中有一个简短的信息:

createNotFoundException()方法创建一个特殊的NotFoundHttpException对象,最终在Symfony内触发404 HTTP响应

在我的脚本中,我这样做:

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException

/**
 * @Route("/{urlSlug}", name="test_member")
 * @Template()
 */
public function showAction($urlSlug) {
    $test = $this->getDoctrine()->.....

    if(!$test) {
        throw new NotFoundHttpException('Sorry not existing!');
    }

    return array(
        'test' => $test
    );
}

+1因为您
抛出
而不是
返回
异常。帮我省了点麻烦。不!它不适用于
返回
,因为它不是有效的
响应
对象<代码>扔掉它,然后快乐地生活。
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException

/**
 * @Route("/{urlSlug}", name="test_member")
 * @Template()
 */
public function showAction($urlSlug) {
    $test = $this->getDoctrine()->.....

    if(!$test) {
        throw new NotFoundHttpException('Sorry not existing!');
    }

    return array(
        'test' => $test
    );
}