From 6019cdeb0ead952a483115e6d8b4b0ac84136861 Mon Sep 17 00:00:00 2001 From: "Gustavo \"Guz\" L de Mello" Date: Wed, 26 Feb 2025 10:47:19 -0300 Subject: [PATCH] feat(smalltrip,exceptions): exception constructor --- exceptions/exceptions.go | 74 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) diff --git a/exceptions/exceptions.go b/exceptions/exceptions.go index fa37c35..cdb11d2 100644 --- a/exceptions/exceptions.go +++ b/exceptions/exceptions.go @@ -50,3 +50,77 @@ func (e Exception) ServeHTTP(w http.ResponseWriter, r *http.Request) { handler(e, w, r) } + +func newException(options ...Option) Exception { + e := Exception{ + Status: http.StatusInternalServerError, + Code: "Internal Server Error", + Message: "", + Err: nil, + Severity: ERROR, + } + + for _, option := range options { + option(&e) + } + + return e +} + +type Option = func(*Exception) + +func WithStatus(s int) Option { + return func(e *Exception) { e.Status = s } +} + +func WithCode(c string) Option { + return func(e *Exception) { e.Code = c } +} + +func WithMessage(m string) Option { + return func(e *Exception) { e.Message = m } +} + +func WithError(err error, errs ...error) Option { + if len(errs) > 0 { + es := []error{err} + es = append(es, errs...) + err = errors.Join(es...) + } + return func(e *Exception) { e.Err = err } +} + +func WithSeverity(s Severity) Option { + return func(e *Exception) { e.Severity = s } +} + +func WithData(key string, v any) Option { + return func(e *Exception) { + if e.Data == nil { + e.Data = make(map[string]any) + } + e.Data[key] = v + } +} + +func WithHeader(header string, v string) Option { + return func(e *Exception) { + if e.headers == nil { + e.headers = http.Header{} + } + e.headers.Add(header, v) + } +} + +func WithoutHeader(header string) Option { + return func(e *Exception) { + if e.headers == nil { + e.headers = http.Header{} + } + e.headers.Del(header) + } +} + +func WithHandler(h HandlerFunc) Option { + return func(e *Exception) { e.handler = h } +}