Errors in Go are values. Effective error handling involves using simple errors, sentinel errors (package-level variables), custom error types for structured data, and error wrapping to preserve context. Use errors.Is and errors.As to inspect errors.
Implement a file validation system using sentinel errors, custom error types, error wrapping, and error inspection.
- Sentinel Errors (Package-level):
ErrEmptyFilename:"filename cannot be empty"ErrFileTooLarge:"file size exceeds limit"
- Custom Error:
ValidationErrorstruct with fieldsFilename(string) andReason(string).- Implement
Error() string: Return"validation failed for '<Filename>': <Reason>".
- Implement
-
ValidateFilename(filename string) error- Return
ErrEmptyFilenameiffilenameis empty. - Return
nilotherwise.
- Return
-
ValidateFileSize(size int64, maxSize int64) error- Return
ErrFileTooLargeifsize > maxSize. - Return new error
"file size cannot be negative"ifsize < 0. - Return
nilotherwise.
- Return
-
ValidateFileExtension(filename string, allowedExts []string) error- Check if
filenameends with any string inallowedExts. - If valid, return
nil. - If invalid, return a
*ValidationErrorwithFilenameset andReasonset to"unsupported file extension".
- Check if
-
ValidateFile(filename string, size int64, maxSize int64) error- Call
ValidateFilename. If error, wrap it with"file validation failed: %w". - Call
ValidateFileSize. If error, wrap it with"file validation failed: %w". - Return
nilif success.
- Call
-
CanRetry(err error) bool- Return
trueiferrwraps a*ValidationError(unsupported extension can be fixed). - Return
falseiferrisnil, or wrapsErrEmptyFilename,ErrFileTooLarge, or any other error.
- Return
- Varies by function.
- Errors (Sentinel, Custom, Wrapped, or simple) and Booleans.
ValidateFilename("")→ErrEmptyFilenameValidateFileSize(200, 100)→ErrFileTooLargeValidateFileExtension("doc.exe", [".txt"])→&ValidationError{"doc.exe", "unsupported file extension"}
To run the tests, execute the following command from the root directory:
go test -v ./quests/014.errorOr from the quest directory:
go test -vExpected output:
=== RUN TestValidateFilename
--- PASS: TestValidateFilename (0.00s)
=== RUN TestValidateFileSize
--- PASS: TestValidateFileSize (0.00s)
=== RUN TestValidateFileExtension
--- PASS: TestValidateFileExtension (0.00s)
=== RUN TestValidateFileWrapping
--- PASS: TestValidateFileWrapping (0.00s)
=== RUN TestCanRetry
--- PASS: TestCanRetry (0.00s)
PASS