Creating Simple Errors
Part of the Fundamentals section of Coddy's GO journey. Lesson 106 of 109.
In Go, you can create custom errors using the errors.New() function from the standard library.
Import the errors package:
import (
"errors"
"fmt"
)Create a simple error with a message:
func divide(a, b int) (int, error) {
if b == 0 {
return 0, errors.New("cannot divide by zero")
}
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 by zeroChallenge
BeginnerIn this challenge, you'll practice creating a simple error in Go using the errors.New() function.
You have a function that checks if a username is valid. A username is considered valid if it has at least 5 characters. Your task is to complete the function by returning an appropriate error when the username is too short.
Try it yourself
package main
import (
"errors"
"fmt"
)
func main() {
// Test with a valid username
result, err := validateUsername("gopher123")
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println(result)
}
// Test with an invalid username
result, err = validateUsername("go")
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println(result)
}
}
func validateUsername(username string) (string, error) {
if len(username) < 5 {
// TODO: Return an error with the message "username must be at least 5 characters long"
// Hint: Use errors.New() to create a new error
return "", nil // Replace this line
}
return "Username is valid", nil
}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