-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjoin.go
64 lines (59 loc) · 2.02 KB
/
join.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package errs
import (
"fmt"
"strings"
)
// JoinError concatenates multiple error messages into a single error object using the specified sep.
// It skips nil errors and ensures a clean, unified error message string.
//
// Parameters:
// - sep: A string representing the sep to be used between the error messages.
// - errors: Variadic arguments representing the errors to be concatenated.
//
// Returns:
// - An error object containing the concatenated error messages, separated by the specified sep.
// If all errors are nil, it returns nil.
// The error object also contains the original error messages in its error string representation.
func Join(sep string, errors ...error) error {
var origErr strings.Builder
var message strings.Builder
for _, err := range errors {
if err != nil {
if origErr.Len() > 0 {
origErr.WriteString(sep) // Append sep between error messages.
message.WriteString(sep) // Append sep between error messages.
}
origErr.WriteString(err.Error()) // Append error message to builder.
message.WriteString(Unwrap(err)) // Append error message to builder.
}
}
if origErr.Len() == 0 {
return nil
}
return &errorString{
origErr: origErr.String(),
message: message.String(),
}
}
// JoinMessages concatenates multiple messages using the specified sep.
// It skips nil values and ensures a clean, unified message string.
//
// Parameters:
// - sep: A string representing the sep to be used between the messages.
// - messages: Variadic arguments representing the messages to be concatenated.
//
// Returns:
// - A string representing the concatenated messages, separated by the specified sep.
// If all messages are nil, an empty string is returned.
func JoinMsg(sep string, a ...any) string {
var builder strings.Builder
for _, message := range a {
if message != nil {
if builder.Len() > 0 {
builder.WriteString(sep) // Append sep between messages.
}
builder.WriteString(fmt.Sprint(message)) // Convert and append message to builder.
}
}
return builder.String()
}