Skip to content

Commit 40c22f4

Browse files
authored
docs(group): explain how group catch-all NotFound routes replace RouteNotFound handlers (#3155)
When a group has middlewares, `Group#Use()` registers catch-all NotFound routes for the group prefix and prefix + `/*` so the middlewares also run for unmatched paths. This is by design (#2411), but the `Group.RouteNotFound` doc did not say so. The note documents which calls register these routes, that the last registered NotFound route for a path wins with only the group middlewares it was registered with, where to register custom handlers, and what to do on routers that do not allow overwriting routes. Refs #3153
1 parent bbc6de8 commit 40c22f4

1 file changed

Lines changed: 11 additions & 0 deletions

File tree

‎group.go‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,17 @@ func (g *Group) File(path, file string, middleware ...MiddlewareFunc) RouteInfo
183183

184184
// RouteNotFound implements `Echo#RouteNotFound()` for sub-routes within the Group.
185185
//
186+
// Important! When the group has middlewares, each `Group#Use()` call (re)registers catch-all NotFound routes for
187+
// the group prefix and prefix + `/*` with the group middlewares, unless the Echo-wide
188+
// `Config.NoGroupAutoRegister404Routes` is set. `Echo#Group()` and `Group#Group()` make this call when the new group
189+
// has own or inherited middlewares. For the same route path the last registered NotFound route wins, and it runs
190+
// only the group middlewares it was registered with: these catch-all routes replace handlers registered earlier for
191+
// those paths (by any group or by Echo), and a handler registered later replaces them. Register custom ones on this
192+
// group after the last such call for its prefix to keep its middlewares. On a Router that does not allow overwriting
193+
// routes this panics; use the router-wide `RouterConfig.NotFoundHandler` there, or set
194+
// `Config.NoGroupAutoRegister404Routes` and register both paths yourself on the group whose middlewares should run
195+
// for them.
196+
//
186197
// Example: `g.RouteNotFound("/*", func(c *echo.Context) error { return c.NoContent(http.StatusNotFound) })`
187198
func (g *Group) RouteNotFound(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfo {
188199
return g.Add(RouteNotFound, path, h, m...)

0 commit comments

Comments
 (0)