Skip to content

Commit e5e8e2d

Browse files
committedDec 20, 2024
implement ErrRequired
1 parent 50bff9b commit e5e8e2d

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed
 

‎required.go

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package errpath
2+
3+
import "strings"
4+
5+
var _ pathWriter = (*ErrRequired)(nil)
6+
7+
// ErrRequired signals that a required value is missing.
8+
type ErrRequired struct{}
9+
10+
// Error fulfills the error interface.
11+
// Without a previous error path, it simply says "a value is required".
12+
// Naturally, this is not very helpful, so it makes sense to wrap `ErrRequired` in another error such as `ErrField` so the user knows that the field was required.
13+
func (e *ErrRequired) Error() string {
14+
b := &strings.Builder{}
15+
b.WriteString("a value")
16+
e.writePath(b)
17+
return b.String()
18+
}
19+
20+
// writePath appends `" is required"` to the path so that the user knows the given path was required
21+
func (e *ErrRequired) writePath(b *strings.Builder) {
22+
b.WriteString(" is required")
23+
}

‎required_test.go

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package errpath_test
2+
3+
import (
4+
"testing"
5+
6+
"github.com/MarkRosemaker/errpath"
7+
)
8+
9+
func TestErrRequired(t *testing.T) {
10+
err := &errpath.ErrRequired{}
11+
if want := `a value is required`; err.Error() != want {
12+
t.Fatalf("want: %s, got: %v", want, err)
13+
}
14+
}

0 commit comments

Comments
 (0)
Please sign in to comment.