将额外参数传递给silex错误处理程序回调函数

时间:2015-08-29 11:19:20

标签: silex

我正在使用Silex和Twig构建一个应用程序,我以这种方式定义路由处理程序(标准方式):

//routes.php
$app->get('/pageA',function () use($app){
  //Display something
});

$app->get('/pageB',function () use($app){
  //Display something
});

$app->post('/pageB',function (Request $req) use($app){
  //Process something
});

然后我设置了一个错误处理程序来管理在路由处理程序中抛出的可能错误,如下所示:

//routes.php
$app->post('/pageB',function (Request $req) use($app){
  //Do something, but an error occurs..
  $app->abort(404,"Page not found");
});

//errors.php
$app->error(function (\Exception $e, $code) use($app) {
  switch($code){
    case 404:
      return $app['twig']->render('404.twig',array('error'=>$e->getMessage()));
    //Other error codes...
    default:
      //return something
  }
});

我想要做的是将一个额外的参数从路由处理程序传递给错误处理程序的回调函数,如下所示:

//routes.php
$app->post('/pageB',function (Request $req) use($app){
  //Do something, but an error occurs..
  $app->abort(404,"Page not found","My extra parameter");
});

//errors.php
$app->error(function (\Exception $e, $code,$extra_param=null) use($app) {
  if(isset($extra_param))
    //Process the error in a different way
  else{ //Standard way
    switch($code){
      case 404:
        return $app['twig']->render('404.twig',array('error'=>$e->getMessage()));
      //Other error codes...
      default:
        //return something
    }
 }
});

可以这样做吗?

1 个答案:

答案 0 :(得分:0)

这可能不是最优雅的解决方案,但您可以将数组添加到$app

$app['my_param_bag'] = array();

$app->get('/pageB', function(Request $request) use ($app) {
  $app['my_param_bag'] = array('foo', 'bar', 'baz');
  $app->abort(404, "Page not found");
});

$app->error(function (\Exception $e, $code) use($app) {
  error_log(print_r($app['my_param_bag'],1).' '.__FILE__.' '.__LINE__,0);

  if(!empty($app['my_param_bag'])) {
    // do something with the params
  }
  else{ 
    switch($code){
      case 404:
        return $app['twig']->render('404.html.twig',array('error'=>$e->getMessage()));
      default:
    }
  }
});

我不确定你的应用程序设置如何,但对我来说,我能够在配置文件中添加这个空数组。

相关问题