refactor: enhance error handling in client creation and context management
All checks were successful
🚀 Publish Release Package / publish (push) Successful in 21s

This commit is contained in:
2025-06-25 12:30:29 -04:00
parent ac789c1cba
commit 95bb27698b
2 changed files with 21 additions and 12 deletions

View File

@@ -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
}