fallback<T extends Object> static method

Route fallback<T extends Object>(
  1. dynamic controller, {
  2. FallbackCondition? when,
})

the route for a GET or HEAD request that matches no other route and no staticFiles file. Use it for a custom 404 page, or to send index.html of a single page app. Other methods still get 404 or 405.

With when, the fallback is tried for a request of any method, and it answers only when when gives true. Use it for a package that answers unknown paths in its own format, like gRPC. Check the method in when when it matters. when also runs for a path that has a route for another method, so a gRPC POST to a path that only has a GET route gets the fallback, not 405. It never runs for a request that a route matches. Routes are sent to every isolate, so when must be a top-level or static function, or one that captures nothing.

Like other routes, it follows group, the router prefix, domain and middleware. So in a router, the global middleware runs for it. Inside a group, it only answers paths under the group prefix. When two fallbacks match, the one with the longest prefix wins.

Route.fallback((DoxRequest req) => res.status(404).json(...));
Route.group('admin', () {
  Route.fallback(controller); // only for /admin/...
});
bool isPost(HttpRequest req) => req.method == 'POST';
Route.fallback(apiNotFound, when: isPost);

Implementation

static Route fallback<T extends Object>(
  dynamic controller, {
  FallbackCondition? when,
}) {
  Route r = Route();
  RouteData data = r._routeData(
    HttpRequestMethod.GET,
    r._join(''),
    _action<T>(controller),
  )..fallbackWhen = when;
  _fallbacks.add(data);
  r._last = data;
  r._lastGroup = null;
  return r;
}