Documentation
¶
Overview ¶
Package errors demonstrates error patterns.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type WriterWithError ¶
type WriterWithError struct {
// contains filtered or unexported fields
}
WriterWithError wraps an io.Writer and stores the error from last failed operation. It allows to avoid systematic Write/if-error checks.
Ref: https://go.dev/blog/errors-are-values
Example ¶
package main
import (
"errors"
"fmt"
dperrors "github.com/skhal/lab/dp/errors"
)
var errBufferFull = errors.New("buffer is full")
type testBuffer struct {
buf []byte
cap int
len int
}
func newTestBuffer(cap int) *testBuffer {
return &testBuffer{
buf: make([]byte, cap),
cap: cap,
}
}
func (tb *testBuffer) Bytes() []byte {
return tb.buf[:tb.len]
}
func (tb *testBuffer) Write(b []byte) (n int, err error) {
n = min(len(b), tb.cap-tb.len)
if n == 0 {
return 0, errBufferFull
}
m := copy(tb.buf[tb.len:tb.cap], b[:n])
tb.len += m
return m, nil
}
func main() {
buf := newTestBuffer(16)
w := dperrors.NewWriterWithError(buf)
w.Write([]byte("hello"))
w.Write([]byte(" "))
w.Write([]byte("world"))
w.Write([]byte(" from a test example"))
w.Write([]byte(" from"))
w.Write([]byte("a test example"))
w.Write([]byte("!"))
if err := w.Err(); err != nil {
fmt.Println("error:", err)
}
fmt.Printf("buffer: %q\n", buf.Bytes())
}
Output: error: buffer is full buffer: "hello world from"
func NewWriterWithError ¶
func NewWriterWithError(w io.Writer) *WriterWithError
NewWriterWithError creates a WriterWithError.
func (*WriterWithError) Err ¶
func (w *WriterWithError) Err() error
Err returns the last error generated by wrapped writer.
Click to show internal directories.
Click to hide internal directories.