Menu
Coddy logo textTech

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 wrong
challenge icon

Challenge

Easy

In 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")
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals