The `error` Interface
Part of the Fundamentals section of Coddy's GO journey — lesson 103 of 109.
In Go, the error interface is a built-in type that represents error conditions. Any type that implements the Error() method satisfies this interface.
Here's the error interface definition:
type error interface {
Error() string
}Create a custom error type:
type MyError struct {
Message string
}
func (e MyError) Error() string {
return e.Message
}
func main() {
err := MyError{Message: "something went wrong"}
fmt.Println(err)
}The output will be:
something went wrongChallenge
EasyIn this challenge, you'll work with Go's error interface. You need to create a custom error using the errors.New() function and then check if an error exists.
The code already has a function that returns an error. Your task is to check if the error is not nil and print an appropriate message.
Cheat sheet
The error interface is a built-in type that represents error conditions. Any type that implements the Error() method satisfies this interface:
type error interface {
Error() string
}Create a custom error type:
type MyError struct {
Message string
}
func (e MyError) Error() string {
return e.Message
}
func main() {
err := MyError{Message: "something went wrong"}
fmt.Println(err) // Output: something went wrong
}Use errors.New() to create simple errors and check if an error is not nil.
Try it yourself
package main
import (
"errors"
"fmt"
)
func main() {
// This function returns an error
err := generateError()
// TODO: Check if err is not nil
// If err is not nil, print: "Error occurred: " followed by the error message
// HINT: Use an if statement to check if err != nil
// This line will only execute if no error occurred
fmt.Println("Program completed successfully")
}
// This function generates an error
func generateError() error {
return errors.New("something went wrong")
}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 Decisions