如何在Symfony2中模拟404错误?

47

所以我正在寻找一种模拟404错误的方法,我尝试了这个:

throw $this->createNotFoundException();  

并且这个

return new Response("",404);

但是没有一个起作用。

1个回答

94

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

http://symfony.com/doc/2.0/book/controller.html

管理错误和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

在我的脚本中,我是这样写的:

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

9
因为你是“抛出”异常而不是“返回”异常,所以我给你点赞。这帮了我省掉了一些麻烦。 - ferdynator
4
不行!使用 return 是不行的,因为它不是一个有效的 Response 对象。用 throw 来解决问题,然后幸福地继续下去。 - ferdynator

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接