| 1 | package standard |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | |
| 6 | "github.com/nicholas-fedor/shoutrrr/internal/failures" |
| 7 | ) |
| 8 | |
| 9 | type failureLike interface { |
| 10 | failures.Failure |
| 11 | } |
| 12 | |
| 13 | const ( |
| 14 | // FailTestSetup is the FailureID used to represent an error that is part of the setup for tests. |
| 15 | FailTestSetup failures.FailureID = -1 |
| 16 | // FailParseURL is the FailureID used to represent failing to parse the service URL. |
| 17 | FailParseURL failures.FailureID = -2 |
| 18 | // FailServiceInit is the FailureID used to represent failure of a service.Initialize method. |
| 19 | FailServiceInit failures.FailureID = -3 |
| 20 | ) |
| 21 | |
| 22 | // FailUnknown is the default FailureID. |
| 23 | const FailUnknown failures.FailureID = iota |
| 24 | |
| 25 | // Failure creates a Failure instance corresponding to the provided failureID, wrapping the provided error. |
| 26 | func Failure(failureID failures.FailureID, err error, args ...any) failures.Failure { |
| 27 | messages := map[int]string{ |
| 28 | int(FailTestSetup): "test setup failed", |
| 29 | int(FailParseURL): "error parsing Service URL", |
| 30 | int(FailUnknown): "an unknown error occurred", |
| 31 | } |
| 32 | |
| 33 | msg := messages[int(failureID)] |
| 34 | if msg == "" { |
| 35 | msg = messages[int(FailUnknown)] |
| 36 | } |
| 37 | |
| 38 | // If variadic arguments are provided, format them correctly |
| 39 | if len(args) > 0 { |
| 40 | if format, ok := args[0].(string); ok && len(args) > 1 { |
| 41 | // Treat the first argument as a format string and the rest as its arguments |
| 42 | extraMsg := fmt.Sprintf(format, args[1:]...) |
| 43 | msg = fmt.Sprintf("%s %s", msg, extraMsg) |
| 44 | } else { |
| 45 | // If no format string is provided, just append the arguments as-is |
| 46 | msg = fmt.Sprintf("%s %v", msg, args) |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | return failures.Wrap(msg, failureID, err) |
| 51 | } |
| 52 | |
| 53 | // IsTestSetupFailure checks whether the given failure is due to the test setup being broken. |
| 54 | func IsTestSetupFailure(failure failureLike) (string, bool) { |
| 55 | if failure != nil && failure.ID() == FailTestSetup { |
| 56 | return "test setup failed: " + failure.Error(), true |
| 57 | } |
| 58 | |
| 59 | return "", false |
| 60 | } |