// Chapter 33 example: the same error, with and without context. // Run with: go run exercises/33/01-add-context.go package main import ( "bufio" "fmt" "os" "strconv" "strings" ) // totalBare adds up the scores in a file, and returns errors as they come. func totalBare(name string) (int, error) { f, err := os.Open(name) if err != nil { return 0, err } defer f.Close() total := 0 scanner := bufio.NewScanner(f) for scanner.Scan() { fields := strings.Fields(scanner.Text()) points, err := strconv.Atoi(fields[1]) if err != nil { return 0, err } total += points } return total, scanner.Err() } // totalWithContext does the same, but says which file and which line. func totalWithContext(name string) (int, error) { f, err := os.Open(name) if err != nil { return 0, err } defer f.Close() total := 0 number := 0 scanner := bufio.NewScanner(f) for scanner.Scan() { number++ fields := strings.Fields(scanner.Text()) points, err := strconv.Atoi(fields[1]) if err != nil { return 0, fmt.Errorf("%s:%d: %w", name, number, err) } total += points } return total, scanner.Err() } func main() { name := "exercises/33/bad-scores.txt" _, err := totalBare(name) fmt.Println("Bare: ", err) _, err = totalWithContext(name) fmt.Println("With context:", err) }