From f28de46379302c2bb5aa17fd150e0d4fe9b2a34e Mon Sep 17 00:00:00 2001 From: Vasiliy Tolstov Date: Mon, 1 Mar 2021 20:23:22 +0300 Subject: [PATCH] dont panic on nil ErrorHandler Signed-off-by: Vasiliy Tolstov --- http.go | 5 +++++ options.go | 12 ++++++++++++ 2 files changed, 17 insertions(+) diff --git a/http.go b/http.go index 6d6e6b3..c7a1b37 100644 --- a/http.go +++ b/http.go @@ -2,6 +2,7 @@ package http import ( + "context" "crypto/tls" "errors" "fmt" @@ -85,6 +86,10 @@ func (h *httpServer) NewHandler(handler interface{}, opts ...server.HandlerOptio sopts: h.opts, } + hdlr.errorHandler = DefaultErrorHandler + if fn, ok := options.Context.Value(errorHandlerKey{}).(func(ctx context.Context, s server.Handler, w http.ResponseWriter, r *http.Request, err error, status int)); ok && fn != nil { + hdlr.errorHandler = fn + } tp := reflect.TypeOf(handler) /* diff --git a/options.go b/options.go index 8c50967..778db51 100644 --- a/options.go +++ b/options.go @@ -13,14 +13,17 @@ type rspCodeVal struct { code int } +// SetError pass error to caller func SetError(err interface{}) error { return &Error{err: err} } +// Error struct holds error type Error struct { err interface{} } +// Error func for error interface func (err *Error) Error() string { return fmt.Sprintf("%v", err.err) } @@ -43,12 +46,21 @@ func GetRspCode(ctx context.Context) int { type middlewareKey struct{} +// Middleware passes http middlewares func Middleware(mw ...func(http.Handler) http.Handler) server.Option { return server.SetOption(middlewareKey{}, mw) } type serverKey struct{} +// Server provide ability to pass *http.Server func Server(hs *http.Server) server.Option { return server.SetOption(serverKey{}, hs) } + +type errorHandlerKey struct{} + +// ErrorHandler specifies handler for errors +func ErrorHandler(fn func(ctx context.Context, s server.Handler, w http.ResponseWriter, r *http.Request, err error, status int)) server.Option { + return server.SetOption(errorHandlerKey{}, fn) +}