Creating Formatted Errors
Part of the Fundamentals section of Coddy's GO journey. Lesson 107 of 109.
Creating Formatted Errors... allows you to include dynamic values in error messages.
The fmt.Errorf() function creates errors with formatted strings, similar to fmt.Printf():
import (
"fmt"
)
func divide(a, b int) (int, error) {
if b == 0 {
return 0, fmt.Errorf("cannot divide %d by zero", a)
}
return a / b, nil
}
func main() {
result, err := divide(10, 0)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Result:", result)
}
}The output will be:
Error: cannot divide 10 by zeroChallenge
BeginnerIn this challenge, you'll practice creating formatted error messages using the fmt.Errorf function. You have a program that validates a username, and you need to create a proper error message when the username is invalid.
The program has a predefined username that's too short (less than 5 characters). Your task is to create a formatted error message that includes the invalid username and the minimum required length.
Try it yourself
package main
import (
"fmt"
)
func main() {
// Predefined username that's too short
username := "bob"
// Minimum required length
minLength := 5
// Check if username is valid
if len(username) < minLength {
// TODO: Create a formatted error using fmt.Errorf that includes:
// 1. The invalid username
// 2. The minimum required length
// Example format: "invalid username: [username] is too short, minimum length is [minLength]"
err := // Your code here
// Print the error
fmt.Println(err)
} else {
fmt.Println("Username is valid!")
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Comparison & Logical Operators
Comparison Operators - Part 1Comparison Operators - Part 2Logical AND OperatorLogical OR OperatorLogical NOT OperatorOperator Precedence BasicsRecap - Making Comparisons7Control Flow: Loops
What The `for` Loop ExplainedFor Loop - BasicFor Loop - Condition OnlyThe `break` KeywordThe `continue` KeywordNested LoopsRecap - Repeating Actions2Variables and Basic Data Types
What is a variableType Inference with `:=`Integers (int)Floating-Point NumbersBooleansStringsZero ValuesConstantsNaming ConventionsRecap - Variables and Types5Basic Input/Output
Formatted OutputFormat VerbsPrinting TypesGetting Basic User InputRecap - Input and Output8Functions
Understanding FunctionsDeclaring a FunctionCalling FunctionsFunction ParametersReturning a Single ValueReturning Multiple ValuesNamed Return ValuesFunction Scope BasicsRecap - Creating Reusable Code11Composite Types: Slices
Introduction to SlicesDeclaring Slice LiteralsCreating Slices with `make`Slice Length vs CapacityAccessing Slice ElementsAppending ElementsSlicing Existing Slices/ArraysIterating Over SlicesCopying SlicesRecap - Dynamic Lists14Basic Error Handling
The Concept of ErrorsThe `error` InterfaceFunctions Returning ErrorsChecking for ErrorsCreating Simple ErrorsCreating Formatted ErrorsBasic Error HandlingRecap - Handling Problems3Basic Operators
Arithmetic OperatorsDivision OperatorThe Modulo OperatorAssignment OperatorAugmented Assignment OperatorsIncrement and DecrementRecap - Calculations6Control Flow: Conditionals
The `if` StatementThe `else` KeywordThe `else if` KeywordVariable Shadowing in `if`Initializing VariablesThe `switch` StatementSwitch with ExpressionsSwitch without ExpressionThe `fallthrough` KeywordRecap - Making DecisionsPractice on your own: Online Go compiler