From 45858f6407856768c159449e00066158c74d1870 Mon Sep 17 00:00:00 2001 From: Henning Rogge Date: Wed, 18 Oct 2023 08:45:54 +0200 Subject: [PATCH 1/3] A bad pattern for a handler is a developer error that can often break whole applications. Panic is more appropriate than just silently logging. --- mux/router.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mux/router.go b/mux/router.go index 5eea8946..7e34356e 100644 --- a/mux/router.go +++ b/mux/router.go @@ -150,7 +150,7 @@ func (r *Router) DefaultHandle(handler Handler) { // HandleFunc adds a handler function to the Router for pattern. func (r *Router) HandleFunc(pattern string, handler func(w ResponseWriter, r *Message)) { if err := r.Handle(pattern, HandlerFunc(handler)); err != nil { - r.errors(fmt.Errorf("cannot handle pattern(%v): %w", pattern, err)) + panic(fmt.Errorf("cannot handle pattern(%v): %w", pattern, err)) } } From f3f608e04f6417bc832b2a449a150e40343efb82 Mon Sep 17 00:00:00 2001 From: Henning Rogge Date: Wed, 18 Oct 2023 08:48:51 +0200 Subject: [PATCH 2/3] Allow user to overwrite mux error handler --- mux/router.go | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/mux/router.go b/mux/router.go index 7e34356e..e3d19986 100644 --- a/mux/router.go +++ b/mux/router.go @@ -81,6 +81,13 @@ func NewRouter() *Router { return router } +// SetErrorHandler sets a custom error handler for the default mux handler set in the constructor. +func (r *Router) SetErrorHandler(h func(error)) { + r.m.Lock() + defer r.m.Unlock() + r.errors = h +} + // Does path match pattern? func pathMatch(pattern Route, path string) bool { return pattern.regexMatcher.regexp.MatchString(path) From 5e22af2ae51201e23e85d8ed470331db45a95c88 Mon Sep 17 00:00:00 2001 From: Henning Rogge Date: Wed, 18 Oct 2023 09:33:48 +0200 Subject: [PATCH 3/3] Add a warning to HandleFunc about the panic --- mux/router.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/mux/router.go b/mux/router.go index e3d19986..fc19b875 100644 --- a/mux/router.go +++ b/mux/router.go @@ -155,6 +155,8 @@ func (r *Router) DefaultHandle(handler Handler) { } // HandleFunc adds a handler function to the Router for pattern. +// This function will panic if the pattern parameter is invalid. If the APP provides 'user defined patterns' better +// use Handle(), which will return an error. func (r *Router) HandleFunc(pattern string, handler func(w ResponseWriter, r *Message)) { if err := r.Handle(pattern, HandlerFunc(handler)); err != nil { panic(fmt.Errorf("cannot handle pattern(%v): %w", pattern, err))