err.gno

1.18 Kb ยท 49 lines
 1// Package pkgerr provides a custom error wrapper that prepends the realm link to your error
 2// This is useful for identifying the source package of the error.
 3//
 4// Usage:
 5//
 6// To wrap an error with realm and chain domain information, use the `New` function:
 7//
 8//	err := pkgerr.New("my error message") // in gno.land/r/leon/example
 9//	fmt.Println(err.Error()) // Output: "r/leon/example: my error message"
10package pkgerr
11
12import (
13	"chain/runtime"
14	"errors"
15	"strings"
16
17	"gno.land/p/nt/ufmt"
18)
19
20// pkgErr is a custom error type that prepends the current
21// realm link to the original error message.
22type pkgErr struct {
23	originalErr error
24}
25
26// New creates a new pkgErr with the given error. The returned error will include
27// the current realm link in its message.
28func New(msg string) error {
29	return &pkgErr{originalErr: errors.New(msg)}
30}
31
32func Wrap(err error) error {
33	if err == nil {
34		return nil
35	}
36
37	return &pkgErr{originalErr: err}
38}
39
40func (e pkgErr) Unwrap() error {
41	return e.originalErr
42}
43
44// Error implements the `error` interface for pkgErr.
45func (e *pkgErr) Error() string {
46	return ufmt.Sprintf("%s: %s",
47		strings.TrimPrefix(runtime.CurrentRealm().PkgPath(), "gno.land/"),
48		e.originalErr)
49}