From 95bb27698b07717d16c49886d504c4b05c5ee9d5 Mon Sep 17 00:00:00 2001 From: Ron Rise Date: Wed, 25 Jun 2025 12:30:29 -0400 Subject: [PATCH] refactor: enhance error handling in client creation and context management --- client/client.go | 28 ++++++++++++++++------------ client/token.go | 5 +++++ 2 files changed, 21 insertions(+), 12 deletions(-) diff --git a/client/client.go b/client/client.go index ca6d04f..c232788 100755 --- a/client/client.go +++ b/client/client.go @@ -1,6 +1,9 @@ package client -import "context" +import ( + "context" + "errors" +) type Client struct { config *Configuration @@ -17,7 +20,7 @@ type accessTokenRequest struct { ClientSecret string `json:"client_secret"` } -func NewClient(config *Configuration) *Client { +func NewClient(config *Configuration) (*Client, error) { client := &Client{ config: config, @@ -25,12 +28,12 @@ func NewClient(config *Configuration) *Client { token, err := getToken(client.config) if err != nil { - return nil + return nil, errors.New("failed to get token: " + err.Error()) } client.token = token - return client + return client, nil } func FromContext(ctx context.Context) *Client { @@ -46,15 +49,16 @@ func FromContext(ctx context.Context) *Client { return nil } -func NewWithContext(ctx context.Context) context.Context { - client := ctx.Value(contextKey) - if client == nil { - return ctx +func NewWithContext(ctx context.Context, config *Configuration) (context.Context, error) { + client, err := NewClient(config) + if err != nil { + return nil, errors.New("failed to create client: " + err.Error()) } - if c, ok := client.(*Client); ok { - return context.WithValue(ctx, contextKey, c) + ctx = context.WithValue(ctx, contextKey, client) + if c, ok := ctx.Value(contextKey).(*Client); ok { + return context.WithValue(ctx, contextKey, c), nil + } else { + return nil, errors.New("failed to set client in context") } - - return ctx } diff --git a/client/token.go b/client/token.go index 4e2353f..918afb4 100755 --- a/client/token.go +++ b/client/token.go @@ -3,6 +3,7 @@ package client import ( "bytes" "encoding/json" + "errors" "gitea.siteworxpro.com/golang-packages/email-api-client/redis" "net/http" "time" @@ -47,6 +48,10 @@ func getToken(configuration *Configuration) (*Token, error) { return nil, err } + if resp.StatusCode != http.StatusOK || resp.ContentLength <= 0 { + return nil, errors.New("Failed to retrieve access token: " + resp.Status) + } + responseBody := make([]byte, resp.ContentLength) _, err = resp.Body.Read(responseBody) if err != nil {