cakephp 路由器::extensions(['json'])对错误控制器没有影响

eblbsuwk  于 2022-11-12  发布在  PHP
关注(0)|答案(1)|浏览(120)

我的目标是在请求时将异常消息转换为JSON(通过头和/或文件扩展名)。根据JSON exception in cakephp 3,这需要在src/Controller/ErrorController.php中进行。如果我简单地将$this->RequestHandler->renderAs($this, 'json')添加到beforeFilter()中,它就可以正常工作,但话又说回来,我应该只在显式请求JSON时才强制JSON。

  • 我首先将Router::extensions(['json'])添加到routes.php的顶部,然后添加this advice
  • 然后,我创建了一个测试操作/foo/bar.json,抛出一个new BadRequestException('hello')
  • 最后,在src/Controller/ErrorController.php中进行调试:
public function beforeRender(Event $event)
{
    parent::beforeRender($event);

    $this->viewBuilder()->setTemplatePath('Error');

    debug($this->getRequest());exit;

}

当我请求它时,我可以看到扩展根本没有被解析:

object(Cake\Http\ServerRequest) {
    [protected] params => [
        'controller' => 'Foo',
        'action' => 'bar.json',
        // …
        '_ext' => null,
    ]

尝试$this->getRequest()->is('json')也会传回false
当我把debug(Router::extensions());exit;添加到config/routes.php的顶部时,什么也没发生。这是否意味着文件根本没有被读取?或者是因为异常在它到达之前就中止了执行?
如何在显式请求时强制显示JSON错误消息?
相关代码:

  • config/routes.php
<?php

  use Cake\Core\Plugin;
  use Cake\Routing\RouteBuilder;
  use Cake\Routing\Router;
  use Cake\Routing\Route\DashedRoute;
  use Cake\Http\Middleware\CsrfProtectionMiddleware;

  Router::extensions(['json']);
  debug(Router::extensions());exit;

  Router::defaultRouteClass(DashedRoute::class);

  Router::scope('/', function (RouteBuilder $routes) {
      $routes->registerMiddleware('csrf', new CsrfProtectionMiddleware());
      $routes->applyMiddleware('csrf');
      $routes->connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']);

      $routes->connect('/pages/*', ['controller' => 'Pages', 'action' => 'display']);

      $routes->fallbacks(DashedRoute::class);
  });

  Router::prefix('abc', function ($routes) {
      $routes->fallbacks(DashedRoute::class);
  });
  Router::prefix('def', function ($routes) {
      $routes->fallbacks(DashedRoute::class);
  });
  Router::prefix('ghi', function ($routes) {
      $routes->fallbacks(DashedRoute::class);
  });
  Router::prefix('api', function ($routes) {
      $routes->prefix('jkl', function ($routes) {
          $routes->fallbacks(DashedRoute::class);
      });
  });
  Router::prefix('mno', function ($routes) {
      $routes->fallbacks(DashedRoute::class);
  });
  //Plugin::routes();
mf98qq94

mf98qq941#

1.在相应的范围内使用setExtensions(),而不是全局调用
1.如果使用前缀,请配置确切的前缀
1.清除该高速缓存:bin/cake cache clear_all
如果操作正确,则不需要额外配置src/Controller/ErrorController.phplike in this answer
工作代码:

Router::prefix('myprefix', function ($routes) {
    $routes->setExtensions(['json']);
    $routes->fallbacks(DashedRoute::class);
});

就是这样,在/myprefix中具有.json扩展名的请求将以JSON的形式返回给抛出异常的操作。

相关问题