Created
January 11, 2024 19:09
-
-
Save jdob/7fa1985e6aac5cd64e48daa9a42924fb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"errors" | |
"os" | |
) | |
// ===== Defines the custom error | |
type ValidationError struct { | |
userMessage string | |
err *error | |
} | |
func (notAnActualError ValidationError) Error() string { | |
return notAnActualError.userMessage | |
} | |
// ===== Interface to all component validation methods | |
type validation func() error | |
// ===== Pretend this is real running code | |
func EibDoingStuff() { | |
err := ValidateDefinition() | |
if err != nil { | |
// WTF do I do with this joined error monstrosity? | |
// Iterate it printing user messages and then exit? | |
} | |
} | |
func ValidateDefinition() error { | |
validations := []validation{ | |
validateOne, | |
validateTwo, | |
} | |
validationErrors := errors.New("validation") | |
for _, v := range validations { | |
err := v() | |
if err != nil { | |
validationErrors = errors.Join(validationErrors, err) | |
} | |
} | |
// How do I determine if no errors were added and return nil instead? | |
return validationErrors | |
} | |
func validateOne() error { | |
// No validation errors found | |
return nil | |
} | |
func validateTwo() error { | |
componentError := errors.New("validateTwo") | |
_, err := os.Stat("main.go") | |
if err != nil { | |
fileError := ValidationError{ | |
userMessage: "The file main.go must be specified but could not be found", | |
err: &err, | |
} | |
componentError = errors.Join(componentError, fileError) | |
} | |
if 1 != 2 { | |
semanticError := ValidationError{ | |
userMessage: "The user violated the basic principles of mathematics", | |
err: nil, // Not strictly needed, right? Since nil would be the default. | |
} | |
componentError = errors.Join(componentError, semanticError) | |
} | |
// Same question, how do I know if I should return nil | |
return componentError | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment