不存在路由的回退路由


Fallback route for routes that do not exist

我在Silex有一个项目,有标准定义的路线,但对于不存在的路线,我想重新路由或转发到主页,或错误页面。

我在文档中没有看到这一点,但我不明白为什么这是不可能的。

我该怎么做?

从Silex Skeleton复制错误处理程序,您可以轻松完成:

<?php
$app->error(function ('Exception $e, Request $request, $code) use ($app) {
    if ($app['debug']) {
        return;
    }
    // 404.html, or 40x.html, or 4xx.html, or error.html
    $templates = array(
            'errors/'.$code.'.html',
            'errors/'.substr($code, 0, 2).'x.html',
            'errors/'.substr($code, 0, 1).'xx.html',
            'errors/default.html',
    );
    return new Response($app['twig']->resolveTemplate($templates)->render(array('code' => $code)), $code);
});

或者,您可能想要重定向/转发(前者往返于浏览器,而后者则不然)。检查文档中的重定向/转发,基本上不需要返回基于渲染模板的响应,只需要return $app->redirectreturn $app->forward

Symfony2有一节关于在Cookbook中自定义错误页面。查看如何自定义错误页面