Created
February 14, 2019 14:28
-
-
Save betandr/af953b8ecfead99a6d7e8d20be7723f4 to your computer and use it in GitHub Desktop.
Writer helper to handle errors
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"io" | |
"os" | |
) | |
func main() { | |
ew := &errWriter{Writer: os.Stdout} | |
fmt.Fprintf(ew, "Hello, World!\n") | |
if ew.err != nil { | |
fmt.Fprintf(os.Stderr, "error: %v\n", ew.err) | |
} | |
} | |
type errWriter struct { | |
io.Writer | |
err error | |
} | |
func (e *errWriter) Write(buf []byte) (int, error) { | |
if e.err != nil { | |
return 0, e.err | |
} | |
var n int | |
n, e.err = e.Writer.Write(buf) | |
return n, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment