【问题标题】:Silex trigger 404 error inside match callbackSilex 在匹配回调中触发 404 错误
【发布时间】:2017-07-26 12:37:24
【问题描述】:

我有这段代码,它匹配来自 json 文件的一些路由:

    $this->app->match($routePattern, function(Request $request, \Silex\Application $app) use($routeIdent, $templateConfig) {

          //now here i need to check some conditions and, 
          //in case, trigger 404 error, but without redirect!!!!

          if($templateConfig['test'] === true){
             //----> TRIGGER 404
          }

    });

有办法处理吗?

【问题讨论】:

    标签: php symfony exception http-status-code-404 silex


    【解决方案1】:

    我不确定我是否正确理解了您的问题。你如果想在if中实现404处理?一种解决方案是在此处返回响应。例如。如果您使用 Symfony\Component\HttpFoundation\Response 对象并内置 twig 服务,您可以这样做:

    use Symfony\Component\HttpFoundation\Response    
    
    $this->app->match($routePattern, function(Request $request, \Silex\Application $app) use($routeIdent, $templateConfig) {
    
        if($templateConfig['test'] === true){
             //----> TRIGGER 404
            return new Response( $app['twig']->render('404.html.twig'), 404); 
        }
    })
    

    我希望这就是你想要的。

    【讨论】:

      【解决方案2】:

      你可以使用abort():

      return $app->abort(404);
      

      返回不是必需的,因为它抛出,我只是更喜欢用它作为一种将它作为退出点的信号方式。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-12
        • 1970-01-01
        • 2010-10-24
        • 2011-09-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多