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:
7
done: invalid ID
true
done: invalid ID: strconv.Atoi: parsing "x": invalid syntax
truepackage 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
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))
}7
done: invalid ID
true
done: invalid ID: strconv.Atoi: parsing "x": invalid syntax
true0 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.
Completion is saved in this browser only. It does not measure mastery.