【发布时间】:2021-07-12 11:14:20
【问题描述】:
我想创建一个与 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 中是不允许的。
不幸的是,这个article 也没有为 Slim 4 提供帮助。
未找到
另外,根据https://www.javaer101.com/en/article/13830039.html,我已经尝试添加
$app->notFound(function () use ($app) {
$app->response->setStatus(403);
echo "Forbidden";
//output 'access denied', redirect to login page or whatever you want to do.
});
到我的 routes.php,但它不起作用:
Call to undefined method Slim\App::notFound()
HttpNotFoundException
最后我也试过创建一个错误处理方法(专门针对HttpNotFoundException,虽然我不知道怎么分离HttpNotImplementedException)https://www.slimframework.com/docs/v4/middleware/error-handling.html,没有任何成功。
非常感谢任何帮助。
【问题讨论】:
标签: php error-handling http-status-code-404 slim slim-4