Skip to content

Instantly share code, notes, and snippets.

@piavgh
Created April 17, 2025 10:04
Show Gist options
  • Save piavgh/e930b9345663dc85c40c8752f6c76b21 to your computer and use it in GitHub Desktop.
Save piavgh/e930b9345663dc85c40c8752f6c76b21 to your computer and use it in GitHub Desktop.
Wrap error
import (
"errors"
"fmt"
"testing"
errorspkg "github.com/pkg/errors"
"github.com/stretchr/testify/assert"
)
func TestErr(t *testing.T) {
ErrTest := errors.New("test error")
ErrTest2 := errors.New("test error 2")
ErrUsingFmt := fmt.Errorf("fmt error: %w", ErrTest)
ErrUsingJoin := errors.Join(ErrTest2, fmt.Errorf("join error: %w", ErrTest))
ErrUsingErrorsPkg := errorspkg.Wrap(ErrTest, "errors pkg error")
fmt.Println("original error: ", errors.Unwrap(ErrUsingFmt))
fmt.Println("1. ErrUsingFmt: ", ErrUsingFmt)
fmt.Println("2. ErrUsingJoin: ", ErrUsingJoin)
fmt.Println("3. ErrUsingErrorsPkg: ", ErrUsingErrorsPkg)
assert.True(t, errors.Is(ErrUsingFmt, ErrTest))
assert.True(t, errors.Is(ErrUsingJoin, ErrTest))
assert.True(t, errors.Is(ErrUsingErrorsPkg, ErrTest))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment