Skip to content

Checkpoint: Validate a Command ID

The Course
•
24 min study
Exercise

Your turn

Write parseID to trim and convert a string, accepting only positive whole numbers. Every failure must match errID, and when the text isn't a number the message should also keep strconv's own explanation. At the caller, wrap the error with the command name done and show that errors.Is still matches. Check " 7 ", "0" and "x". The output should be:

Text
7
done: invalid ID
true
done: invalid ID: strconv.Atoi: parsing "x": invalid syntax
true
Your working space Go
package main

func main() {
	// Build your solution here.
}
Hint 1: the idea

There are two ways to fail: text that isn't a number, and a number outside the allowed range. Both report errID, but only the first has a cause worth showing.

Hint 2: a first step

Use strconv.Atoi after strings.TrimSpace and return errID for any failure. Check " 7 " and "0" first, then make the "x" case keep strconv's message.

Worked solution
Run the solution Go
package main

import (
	"errors"
	"fmt"
	"strconv"
	"strings"
)

var errID = errors.New("invalid ID")

func parseID(text string) (int, error) {
	id, err := strconv.Atoi(strings.TrimSpace(text))
	if err != nil {
		return 0, fmt.Errorf("%w: %v", errID, err)
	}
	if id <= 0 {
		return 0, errID
	}
	return id, nil
}

func main() {
	id, err := parseID(" 7 ")
	if err != nil {
		panic(err)
	}
	fmt.Println(id)
	_, err = parseID("0")
	err = fmt.Errorf("done: %w", err)
	fmt.Println(err)
	fmt.Println(errors.Is(err, errID))
	_, err = parseID("x")
	err = fmt.Errorf("done: %w", err)
	fmt.Println(err)
	fmt.Println(errors.Is(err, errID))
}
Text
7
done: invalid ID
true
done: invalid ID: strconv.Atoi: parsing "x": invalid syntax
true

0 converts cleanly but fails the range check, so it returns plain errID. For "x", errID is wrapped with %w, so callers can still match it, and strconv's error is added with %v, so a person reading the message sees exactly what was wrong. Callers only need to test for errID, so strconv's text is enough there. Wrapping again with done: hides neither.

Was this article helpful?

Your response is saved on this device.