errors

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 24, 2026 License: BSD-3-Clause Imports: 1 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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.

func (*WriterWithError) Write

func (w *WriterWithError) Write(p []byte) (n int, err error)

Write implement io.Writer interface.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL