Slim 4 PHP中的默认路由/notFound错误处理/HttpNotFoundException

Slim 4 PHP中的默认路由/notFound错误处理/HttpNotFoundException,php,error-handling,http-status-code-404,slim,slim-4,Php,Error Handling,Http Status Code 404,Slim,Slim 4,我想创建一个Slim 4兼容的自定义错误页/JSON回复,当请求不存在路由时返回该回复 默认路由(Slim 3) 我最近从Slim 3升级到Slim 4。对于Slim 3,我有一个默认路线,它完美地完成了任务: $app->any('/[{path:.*}]', function (Request $request, Response $response, array $args) { // catching any other requests... /*

我想创建一个Slim 4兼容的自定义错误页/JSON回复,当请求不存在路由时返回该回复

默认路由(Slim 3) 我最近从Slim 3升级到Slim 4。对于Slim 3,我有一个默认路线,它完美地完成了任务:

   $app->any('/[{path:.*}]', function (Request $request, Response $response, array $args) {
      // catching any other requests...
      /* ... creating JSON error object and write it to $slimresponse ... */
      return ($slimresponse);
   });
然而,当我在Slim 4中执行此操作时,我会得到一个错误

Type: FastRoute\BadRouteException
Code: 0
Message: Cannot register two routes matching "/" for method "GET"
这显然意味着Slim将其识别为GET/的双条目,这在Slim 4中是不允许的

不幸的是,这对Slim 4也没有帮助

未找到 此外,据我所知,我试图补充

$app->notFound(function () use ($app) {
    $app->response->setStatus(403);
    echo "Forbidden";
    //output 'access denied', redirect to login page or whatever you want to do.
});
到my routes.php,但它不起作用:

Call to undefined method Slim\App::notFound()
HttpNotFoundException 最后,我还尝试创建一个错误处理方法(专门针对HttpNotFoundException,尽管我不知道如何分离HttpNotImplementedException),但没有成功


非常感谢您的帮助。

我在搜索了两个多小时后发布了这个问题

提交问题后,我在这里找到了答案。

下面是我的新middleware.php:

return function (App $app) {
    // Parse json, form data and xml
    $app->addBodyParsingMiddleware();

    // Add the Slim built-in routing middleware
    $app->addRoutingMiddleware();

    // always add a trailing slash
    $app->add(new TrailingSlash(true));

    // Add BasePathMiddleware
    $app->add(BasePathMiddleware::class);

    // HttpNotFoundException
    $app->add(function (
       ServerRequestInterface $request, 
       RequestHandlerInterface $handler
       ) {
       try {
          return $handler->handle($request);
       } catch (HttpNotFoundException $httpException) {
           $response = (new Response())->withStatus(404);
           $response->getBody()->write('404 Not found');

           return $response;
       }
    });

    // Catch exceptions and errors
    $app->add(ErrorMiddleware::class);
};