如何使用Symfony2模拟404错误?

Rac*_*naa 41 symfony symfony-2.1

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

throw $this->createNotFoundException();  
Run Code Online (Sandbox Code Playgroud)

还有这个

return new Response("",404);
Run Code Online (Sandbox Code Playgroud)

但没有一个可行.

Ren*_*hle 83

您可以在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(...);
}
Run Code Online (Sandbox Code Playgroud)

文档中有一个简短的信息:

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

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException
Run Code Online (Sandbox Code Playgroud)

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

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
    );
}
Run Code Online (Sandbox Code Playgroud)

  • +1因为你'抛出`而不是'返回'异常.救了我一些麻烦. (8认同)
  • 没有!它不适用于`return`,因为它不是一个有效的`Response`对象.扔掉它,然后快乐地生活. (3认同)