Skip to content

Commit f947f81

Browse files
committed
Add error handling to fmt.Fprintln()
1 parent 401c362 commit f947f81

File tree

1 file changed

+22
-9
lines changed

1 file changed

+22
-9
lines changed

kadai3-1/lfcd85/typinggame/typinggame.go

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ import (
88
"math/rand"
99
"os"
1010
"time"
11+
12+
"github.com/hashicorp/go-multierror"
1113
)
1214

1315
// Words stores a slice of words which is used for the game.
@@ -21,38 +23,42 @@ type Game struct {
2123

2224
// Execute starts the game using standard input and output.
2325
func Execute(g Game) error {
24-
g.run(inputChannel(os.Stdin), os.Stdout)
25-
return nil
26+
err := g.run(inputChannel(os.Stdin), os.Stdout)
27+
return err
2628
}
2729

28-
func (g *Game) run(ch <-chan string, w io.Writer) {
30+
func (g *Game) run(ch <-chan string, w io.Writer) error {
31+
var result error
32+
2933
bc := context.Background()
3034
ctx, cancel := context.WithTimeout(bc, g.TimeLimit)
3135
defer cancel()
3236

33-
fmt.Fprintln(w, "Let's type the standard package names! ( Time limit:", g.TimeLimit, ")")
37+
result = printWithMultiErr(w, result, "Let's type the standard package names! ( Time limit:", g.TimeLimit, ")")
3438

3539
var score int
3640
rand.Seed(time.Now().UnixNano())
3741
word := g.Words[rand.Intn(len(g.Words))]
3842
LOOP:
3943
for {
40-
fmt.Fprintln(w, ">", word)
44+
result = printWithMultiErr(w, result, ">", word)
4145
select {
4246
case input := <-ch:
4347
if input == word {
4448
score++
45-
fmt.Fprintln(w, input, "... OK! current score:", score)
49+
result = printWithMultiErr(w, result, input, "... OK! current score:", score)
4650
word = g.Words[rand.Intn(len(g.Words))]
4751
} else {
48-
fmt.Fprintln(w, input, "... NG: try again.")
52+
result = printWithMultiErr(w, result, input, "... NG: try again.")
4953
}
5054
case <-ctx.Done():
51-
fmt.Fprintln(w)
52-
fmt.Fprintln(w, g.TimeLimit, "has passed: you correctly typed", score, "package(s)!")
55+
result = printWithMultiErr(w, result)
56+
result = printWithMultiErr(w, result, g.TimeLimit, "has passed: you correctly typed", score, "package(s)!")
5357
break LOOP
5458
}
5559
}
60+
61+
return result
5662
}
5763

5864
func inputChannel(r io.Reader) <-chan string {
@@ -66,3 +72,10 @@ func inputChannel(r io.Reader) <-chan string {
6672
}()
6773
return ch
6874
}
75+
76+
func printWithMultiErr(w io.Writer, result error, a ...interface{}) error {
77+
if _, err := fmt.Fprintln(w, a...); err != nil {
78+
result = multierror.Append(result, err)
79+
}
80+
return result
81+
}

0 commit comments

Comments
 (0)