Menu
Coddy logo textTech

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

Challenge

Beginner

In 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.

Cheat sheet

Use fmt.Errorf() to create formatted error messages with dynamic values:

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
}

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

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

All lessons in Fundamentals