From 644ea5d2338f8290325f982af5d32e90acc64416 Mon Sep 17 00:00:00 2001 From: Henning Rogge Date: Wed, 18 Oct 2023 11:38:30 +0200 Subject: [PATCH] Improve mux errors (#495) * A bad pattern for a handler is a developer error that can often break whole applications. Panic is more appropriate than just silently logging. * Allow user to overwrite mux error handler * Add a warning to HandleFunc about the panic --- mux/router.go | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/mux/router.go b/mux/router.go index 5eea8946..fc19b875 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) @@ -148,9 +155,11 @@ 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 { - r.errors(fmt.Errorf("cannot handle pattern(%v): %w", pattern, err)) + panic(fmt.Errorf("cannot handle pattern(%v): %w", pattern, err)) } }