From e6361918d4ae6feb135f49e048e862ddf4daaddd Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Franc=C3=A9=20Wilke?= <francewilke@gmail.com>
Date: Wed, 22 Jan 2025 13:16:25 +0200
Subject: [PATCH] Change ErrorWithMsg and ErrorWithFields to cater for
 formatting directives

---
 api_documentation/api_documentation.go |  2 +-
 api_responses/api_responses.go         | 16 ++++++++--------
 audit/audit.go                         |  4 ++--
 batch/batch.go                         |  2 +-
 encryption/encryption_keys.go          |  2 +-
 logs/logs_test.go                      |  6 +++---
 redis/redis.go                         | 16 ++++++++--------
 ses/ses.go                             |  9 ++++-----
 slack_utils/slack_utils.go             |  4 ++--
 sqs/sqs.go                             |  8 ++++----
 10 files changed, 34 insertions(+), 35 deletions(-)

diff --git a/api_documentation/api_documentation.go b/api_documentation/api_documentation.go
index 2322c36..d7c17eb 100644
--- a/api_documentation/api_documentation.go
+++ b/api_documentation/api_documentation.go
@@ -423,7 +423,7 @@ func GetStructDocs(corePath string) map[string]string {
 
 	err := filepath.Walk(corePath, walkFunction)
 	if err != nil {
-		logs.ErrorWithMsg("Failed to upload files to s3", err)
+		logs.ErrorWithMsg(err, "Failed to upload files to s3")
 	}
 
 	return docs
diff --git a/api_responses/api_responses.go b/api_responses/api_responses.go
index 0f63255..71cee6f 100644
--- a/api_responses/api_responses.go
+++ b/api_responses/api_responses.go
@@ -36,11 +36,11 @@ func ServerError(err error, msg string) (events.APIGatewayProxyResponse, error)
 }
 
 func Error(err error, msg string, statusCode int) (events.APIGatewayProxyResponse, error) {
-	logs.ErrorWithFields(map[string]interface{}{
+	logs.ErrorWithFields(err, map[string]interface{}{
 		"type":    "Server error",
 		"message": msg,
 		"code":    statusCode,
-	}, err)
+	})
 
 	serverError := errorMsg{
 		Message: msg,
@@ -81,11 +81,11 @@ func DatabaseServerErrorNew(err error, msg string) error {
 	} else if statusCode == http.StatusConflict {
 		logs.Info("Database conflict: " + msg + ". Code: " + strconv.Itoa(statusCode))
 	} else {
-		logs.ErrorWithFields(map[string]interface{}{
+		logs.ErrorWithFields(err, map[string]interface{}{
 			"type":    "Database error",
 			"message": msg,
 			"code":    statusCode,
-		}, err)
+		})
 	}
 
 	return ServerErrorStruct{
@@ -125,11 +125,11 @@ func DatabaseServerError(err error, msg string) (events.APIGatewayProxyResponse,
 	} else if statusCode == http.StatusConflict {
 		logs.Info("Database conflict: " + msg + ". Code: " + strconv.Itoa(statusCode))
 	} else {
-		logs.ErrorWithFields(map[string]interface{}{
+		logs.ErrorWithFields(err, map[string]interface{}{
 			"type":    "Database error",
 			"message": msg,
 			"code":    statusCode,
-		}, err)
+		})
 	}
 
 	serverError := errorMsg{
@@ -220,10 +220,10 @@ func trimBrackets(value string) string {
 
 // ClientError creates responses due to request client error
 func ClientError(status int, message string) (events.APIGatewayProxyResponse, error) {
-	logs.WarnWithFields(map[string]interface{}{
+	logs.WarnWithFields(errors.Error(message), map[string]interface{}{
 		"type": "Client error",
 		"code": status,
-	}, errors.Error(message))
+	})
 
 	e := errorMsg{
 		Message: message,
diff --git a/audit/audit.go b/audit/audit.go
index a766d40..06b4d2d 100644
--- a/audit/audit.go
+++ b/audit/audit.go
@@ -235,13 +235,13 @@ func CheckToFormatForAuditEvent(changes map[string]any, original any, new any, f
 
 	defer func() {
 		if err := recover(); err != nil {
-			logs.ErrorWithFields(map[string]any{
+			logs.ErrorWithFields(errors.Error("Failed to format for audit event"), map[string]any{
 				"error":    err,
 				"field":    field,
 				"index":    index,
 				"original": fmt.Sprintf("%#v", originalFieldValue),
 				"new":      fmt.Sprintf("%#v", newFieldValue),
-			}, errors.Error("Failed to format for audit event"))
+			})
 			didInsert = false
 		}
 	}()
diff --git a/batch/batch.go b/batch/batch.go
index 7bc147d..63f53d1 100644
--- a/batch/batch.go
+++ b/batch/batch.go
@@ -126,7 +126,7 @@ func RetrieveMessageFromS3(filename string, messagesBucketName string, isDebug b
 	var bodyBytes []byte
 	bodyBytes, err = io.ReadAll(rawObject.Body)
 	if err != nil {
-		logs.ErrorWithMsg("Could not read file", err)
+		logs.ErrorWithMsg(err, "Could not read file")
 		return bodyBytes, err
 	}
 	return bodyBytes, nil
diff --git a/encryption/encryption_keys.go b/encryption/encryption_keys.go
index 6b0f9ec..d981588 100644
--- a/encryption/encryption_keys.go
+++ b/encryption/encryption_keys.go
@@ -37,7 +37,7 @@ func GetEncryptionKeys(secretID string, isDebug bool) (EncryptionKeys, error) {
 func GetJWTEncryptionKey(secretID string, isDebug bool) (string, error) {
 	encryptionKeys, err := GetEncryptionKeys(secretID, isDebug)
 	if err != nil {
-		logs.ErrorWithMsg("Could not get encryption keys from secret manager", err)
+		logs.ErrorWithMsg(err, "Could not get encryption keys from secret manager")
 		return "", errors.Error("failed to get encryption keys for login")
 	}
 	return encryptionKeys.JWTEncryptionKey, nil
diff --git a/logs/logs_test.go b/logs/logs_test.go
index 4abfb86..1aaac22 100644
--- a/logs/logs_test.go
+++ b/logs/logs_test.go
@@ -19,10 +19,10 @@ func TestLogs(t *testing.T) {
 
 	logs.InfoWithFields(map[string]interface{}{"a": 1, "b": 2}, "MyLogMessage1")
 	logs.Info("MyLogMessage2=%d,%d,%d", 1, 2, 3)
-	logs.ErrorWithFields(map[string]interface{}{"a": 4, "b": 5}, errors.Errorf("simple mistake"))
-	logs.ErrorWithMsg("Error Message", errors.Errorf("another simple mistake"))
+	logs.ErrorWithFields(errors.Errorf("simple mistake"), map[string]interface{}{"a": 4, "b": 5})
+	logs.ErrorWithMsg(errors.Errorf("another simple mistake"), "Error Message")
 	logs.Warn("Warning about a=%s,%s,%s", "a", "b", "c")
-	logs.WarnWithFields(map[string]interface{}{"a": 4, "b": 5}, errors.Errorf("Cant believe it failed"))
+	logs.WarnWithFields(errors.Errorf("Cant believe it failed"), map[string]interface{}{"a": 4, "b": 5})
 	logs.SQLDebugInfo("SELECT * from user")
 	// logs.LogRequestInfo(event)
 	// api_logs.LogSQSEvent(sqsEvent)
diff --git a/redis/redis.go b/redis/redis.go
index 98972ed..8b6f3ee 100644
--- a/redis/redis.go
+++ b/redis/redis.go
@@ -124,13 +124,13 @@ func (r ClientWithHelpers) SetObjectByKey(key string, object interface{}) {
 
 	jsonBytes, err := json.Marshal(object)
 	if err != nil {
-		logs.ErrorWithMsg("Error marshalling object to Redis: %s", err)
+		logs.ErrorWithMsg(err, "Error marshalling object to Redis: %s")
 		return
 	}
 
 	_, err = r.Client.Set(ctx, key, string(jsonBytes), 24*time.Hour).Result()
 	if err != nil {
-		logs.ErrorWithMsg(fmt.Sprintf("Error setting value to Redis for key: %s", key), err)
+		logs.ErrorWithMsg(err, "Error setting value to Redis for key: %s", key)
 
 		/* Prevent further calls in this execution from trying to connect and also timeout */
 		if strings.HasSuffix(err.Error(), "i/o timeout") {
@@ -146,13 +146,13 @@ func (r ClientWithHelpers) SetObjectByKeyWithExpiry(key string, object interface
 
 	jsonBytes, err := json.Marshal(object)
 	if err != nil {
-		logs.ErrorWithMsg("Error marshalling object to Redis: %s", err)
+		logs.ErrorWithMsg(err, "Error marshalling object to Redis: %s")
 		return
 	}
 
 	_, err = r.Client.Set(ctx, key, string(jsonBytes), expiration).Result()
 	if err != nil {
-		logs.ErrorWithMsg(fmt.Sprintf("Error setting value to Redis for key: %s", key), err)
+		logs.ErrorWithMsg(err, "Error setting value to Redis for key: %s", key)
 
 		/* Prevent further calls in this execution from trying to connect and also timeout */
 		if strings.HasSuffix(err.Error(), "i/o timeout") {
@@ -168,13 +168,13 @@ func (r ClientWithHelpers) SetObjectByKeyIndefinitely(key string, object interfa
 
 	jsonBytes, err := json.Marshal(object)
 	if err != nil {
-		logs.ErrorWithMsg("Error marshalling object to Redis", err)
+		logs.ErrorWithMsg(err, "Error marshalling object to Redis")
 		return
 	}
 
 	_, err = r.Client.Set(ctx, key, string(jsonBytes), 0).Result()
 	if err != nil {
-		logs.ErrorWithMsg(fmt.Sprintf("Error setting value to Redis for key: %s", key), err)
+		logs.ErrorWithMsg(err, "Error setting value to Redis for key: %s", key)
 
 		/* Prevent further calls in this execution from trying to connect and also timeout */
 		if strings.HasSuffix(err.Error(), "i/o timeout") {
@@ -237,7 +237,7 @@ func (r ClientWithHelpers) RateLimit(key string, limitFn func(int) redis_rate.Li
 	limiter := redis_rate.NewLimiter(r.Client)
 	res, err := limiter.Allow(ctx, key, limitFn(limit))
 	if err != nil {
-		logs.ErrorWithMsg(fmt.Sprintf("Redis Error rate limiting - %s", key), err)
+		logs.ErrorWithMsg(err, "Redis Error rate limiting - %s", key)
 
 		/* Prevent further calls in this execution from trying to connect and also timeout */
 		if strings.HasSuffix(err.Error(), "i/o timeout") {
@@ -280,7 +280,7 @@ func (r ClientWithHelpers) SetLockKey(key string, expiration time.Duration, lock
 	for retries >= 0 {
 		success, err = r.Client.SetNX(ctx, key, value, expiration).Result()
 		if err != nil {
-			logs.ErrorWithMsg(fmt.Sprintf("Error setting lock key %s", key), err)
+			logs.ErrorWithMsg(err, "Error setting lock key %s", key)
 
 			// Prevent further calls in this execution from trying to connect and also timeout
 			if strings.HasSuffix(err.Error(), "i/o timeout") {
diff --git a/ses/ses.go b/ses/ses.go
index 3b281ca..be6a991 100644
--- a/ses/ses.go
+++ b/ses/ses.go
@@ -3,7 +3,6 @@ package ses
 import (
 	"bytes"
 	"context"
-	"fmt"
 	"github.com/aws/aws-sdk-go-v2/aws"
 	"github.com/aws/aws-sdk-go-v2/config"
 	"github.com/aws/aws-sdk-go-v2/service/ses"
@@ -151,13 +150,13 @@ func (c *ClientWithHelpers) SendEmail(email Email, emfNamespace string, isDebug
 
 		switch errors.AWSErrorExceptionCode(err) {
 		case messageRejectedErrorCode, mailFromDomainNotVerifiedErrorCode, configurationSetDoesNotExistErrorCode:
-			logs.ErrorWithMsg(errors.AWSErrorExceptionCode(err), err)
+			logs.ErrorWithMsg(err, errors.AWSErrorExceptionCode(err))
 		case InvalidParameterValueErrorString:
 			// Ignore errors due to invalid email addresses - we don't want to log it to raygun
 			logs.Warn(err.Error())
 			err = nil
 		default:
-			logs.ErrorWithMsg("Failed to send email", err)
+			logs.ErrorWithMsg(err, "Failed to send email")
 		}
 
 		if emfNamespace != "" {
@@ -187,14 +186,14 @@ func addAttachmentsToEmail(msg *gomail.Message, attachment s3.S3UploadResponse,
 	// Get object from S3
 	object, err := s3.GetClient(isDebug).GetObject(attachment.Bucket, attachment.Filename, isDebug)
 	if err != nil {
-		logs.ErrorWithMsg(fmt.Sprintf("Failed to get S3 object from bucket %s filename %s", attachment.Bucket, attachment.Filename), err)
+		logs.ErrorWithMsg(err, "Failed to get S3 object from bucket %s filename %s", attachment.Bucket, attachment.Filename)
 		return err
 	}
 	defer object.Body.Close()
 
 	attachmentBytes, err := io.ReadAll(object.Body)
 	if err != nil {
-		logs.ErrorWithMsg("Could not encode attachment for email", err)
+		logs.ErrorWithMsg(err, "Could not encode attachment for email")
 		return err
 	}
 
diff --git a/slack_utils/slack_utils.go b/slack_utils/slack_utils.go
index 1d35bc1..f3ca9ec 100644
--- a/slack_utils/slack_utils.go
+++ b/slack_utils/slack_utils.go
@@ -47,7 +47,7 @@ func (s *SlackClient) SendAlertWithFields(message string, channel string, slackF
 	if s == nil || s.Client == nil {
 		// If the slack client isn't set, log the message to Raygun instead
 		slackFieldMap := slackFieldsToMap(slackFields)
-		logs.ErrorWithFields(slackFieldMap, errors.Error(message))
+		logs.ErrorWithFields(errors.Error(message), slackFieldMap)
 		return ""
 	}
 
@@ -111,7 +111,7 @@ func (s *SlackClient) SendAlertWithFields(message string, channel string, slackF
 func (s *SlackClient) postMessage(channel string, messageOptions []slack.MsgOption) string {
 	_, messageTimestamp, err := s.Client.PostMessage(channel, messageOptions...)
 	if err != nil {
-		logs.ErrorWithMsg("Error sending slack: %v+\n", err)
+		logs.ErrorWithMsg(err, "Error sending slack:")
 	}
 	return messageTimestamp
 }
diff --git a/sqs/sqs.go b/sqs/sqs.go
index c1d8619..a514082 100644
--- a/sqs/sqs.go
+++ b/sqs/sqs.go
@@ -131,13 +131,13 @@ func SendSQSMessage(msgr Messenger, objectToSend interface{}, currentRequestID *
 		var err error
 		sqsClient, err = NewSQSClient(msgr.Region)
 		if err != nil {
-			logs.ErrorWithMsg("Failed to create sqs client", err)
+			logs.ErrorWithMsg(err, "Failed to create sqs client")
 		}
 	}
 
 	jsonBytes, err := json.Marshal(objectToSend)
 	if err != nil {
-		logs.ErrorWithMsg("Failed to encode sqs event data", err)
+		logs.ErrorWithMsg(err, "Failed to encode sqs event data")
 		return err
 	}
 
@@ -165,7 +165,7 @@ func SendSQSMessage(msgr Messenger, objectToSend interface{}, currentRequestID *
 
 	msgID, err := msgr.SendSQSMessage(headers, message, currentRequestID, sqsType)
 	if err != nil {
-		logs.ErrorWithMsg("Failed to send sqs event", err)
+		logs.ErrorWithMsg(err, "Failed to send sqs event")
 		return err
 	}
 
@@ -197,7 +197,7 @@ func RetrieveMessageFromS3(client *s3.ClientWithHelpers, bucket string, filename
 	var bodyBytes []byte
 	bodyBytes, err = io.ReadAll(rawObject.Body)
 	if err != nil {
-		logs.ErrorWithMsg("Could not read file", err)
+		logs.ErrorWithMsg(err, "Could not read file")
 		return []byte{}, err
 	}
 
-- 
GitLab