Menu
Coddy logo textTech

Functions Returning Errors

Part of the Fundamentals section of Coddy's GO journey — lesson 104 of 109.

In Go, functions commonly return an error as their last return value to indicate if something went wrong.

Create a function that returns both a result and an error:

func divide(a, b float64) (float64, error) {
    if b == 0 {
        return 0, errors.New("cannot divide by zero")
    }
    return a / b, nil
}

Call the function and handle the error:

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

Challenge

Beginner

In this challenge, you'll practice creating a function that returns an error when invalid input is provided.

You need to complete the validateUsername function that checks if a username is valid. A username is valid if it's at least 3 characters long. If the username is valid, return nil for the error. If it's invalid, return an error with an appropriate message.

The code to call your function and handle the error is already written for you.

Note: This challenge uses predefined variables instead of user input.

Cheat sheet

Functions in Go commonly return an error as their last return value to indicate if something went wrong.

Create a function that returns both a result and an error:

func divide(a, b float64) (float64, error) {
    if b == 0 {
        return 0, errors.New("cannot divide by zero")
    }
    return a / b, nil
}

Handle the error when calling the function:

result, err := divide(10, 0)
if err != nil {
    fmt.Println("Error:", err)
} else {
    fmt.Println("Result:", result)
}

Return nil when there's no error, and use errors.New() to create error messages.

Try it yourself

package main

import (
	"errors"
	"fmt"
)

func validateUsername(username string) error {
	// TODO: Check if the username length is less than 3 characters
	// If it is, return an error with the message "username too short"
	// Otherwise, return nil (no error)
	
	return nil
}

func main() {
	// Test with a valid username
	validName := "bob123"
	err1 := validateUsername(validName)
	if err1 != nil {
		fmt.Printf("%s is invalid: %v\n", validName, err1)
	} else {
		fmt.Printf("%s is valid!\n", validName)
	}
	
	// Test with an invalid username
	invalidName := "ab"
	err2 := validateUsername(invalidName)
	if err2 != nil {
		fmt.Printf("%s is invalid: %v\n", invalidName, err2)
	} else {
		fmt.Printf("%s is valid!\n", invalidName)
	}
}
quiz iconTest yourself

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

All lessons in Fundamentals