summaryrefslogtreecommitdiff
path: root/internal/types
diff options
context:
space:
mode:
authorjwijenbergh <jeroenwijenbergh@protonmail.com>2022-06-20 15:20:18 +0200
committerjwijenbergh <jeroenwijenbergh@protonmail.com>2022-06-20 15:20:18 +0200
commit2252135fadb8c579ad27345e3203be755130e3cd (patch)
treeed5a530e85b43736fc0bc28c927cfa8488f9199b /internal/types
parent7af07c596166bf93b79a9d0816b1950dde360fb9 (diff)
Refactor: Errors to have one custom type that is to be wrapped
- For this an `internal/types` package is created with a custom error type - This custom error type can give back the cause and traceback of an error
Diffstat (limited to 'internal/types')
-rw-r--r--internal/types/error.go62
1 files changed, 62 insertions, 0 deletions
diff --git a/internal/types/error.go b/internal/types/error.go
new file mode 100644
index 0000000..fda7c9c
--- /dev/null
+++ b/internal/types/error.go
@@ -0,0 +1,62 @@
+package types
+
+import (
+ "errors"
+ "fmt"
+)
+
+type WrappedErrorMessage struct {
+ Message string
+ Err error
+}
+
+func (e *WrappedErrorMessage) Unwrap() error {
+ return e.Err
+}
+
+func (e *WrappedErrorMessage) Cause() error {
+ causeErr := e.Err
+ for errors.Unwrap(causeErr) != nil {
+ causeErr = errors.Unwrap(causeErr)
+ }
+ return causeErr
+}
+
+func (e *WrappedErrorMessage) Traceback() string {
+ returnStr := fmt.Sprintf("Traceback for error: %s", e.Message)
+ causeErr := e.Err
+ for errors.Unwrap(causeErr) != nil {
+ causeErr = errors.Unwrap(causeErr)
+ var wrappedErr *WrappedErrorMessage
+
+ errorStr := causeErr.Error()
+
+ if errors.As(causeErr, &wrappedErr) {
+ errorStr = wrappedErr.Message
+ }
+ returnStr += fmt.Sprintf("\n - %s", errorStr)
+ }
+ return returnStr
+}
+
+func (e *WrappedErrorMessage) Error() string {
+ return fmt.Sprintf("Got error: %s, with cause: %s", e.Message, e.Err)
+}
+
+func GetErrorTraceback(err error) string {
+ var wrappedErr *WrappedErrorMessage
+
+ if errors.As(err, &wrappedErr) {
+ return wrappedErr.Traceback()
+ }
+ return err.Error()
+}
+
+func GetErrorCause(err error) error {
+ var wrappedErr *WrappedErrorMessage
+
+ if errors.As(err, &wrappedErr) {
+ return wrappedErr.Cause()
+ }
+ return err
+}