Menu
Coddy logo textTech

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

Challenge

Beginner

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

Cheat sheet

Create custom errors using errors.New() from the standard library:

import (
    "errors"
    "fmt"
)

Return an error from a function:

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

Handle the error:

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

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

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

All lessons in Fundamentals