nobrandheroes
nobrandheroes

Reputation: 758

Fallback route for routes that do not exist

I have a project in Silex, with the standard defined routes, but for routes that do not exist, I would like to reroute or forward to the homepage, or an error page.

I'm not seeing this in the documentation, but I don't see why this isn't possible.

How do I do this?

Upvotes: 0

Views: 196

Answers (2)

mTorres
mTorres

Reputation: 3590

Copying the error handler from Silex Skeleton, you can do it easily:

<?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);
});

Or you may want to redirect / forward (the former does a round trip to the browser whereas the latter does not). Check the docs for the redirect / forward, basically instead of returning a response based on a rendered template you just need to return $app->redirect or return $app->forward

Upvotes: 1

Peky
Peky

Reputation: 449

Symfony2 has section about customizing error pages in Cookbook. Look at How to Customize Error Pages

Upvotes: 0

Related Questions