Skip to content

Commit

Permalink
MustProcess: panic if processing fails, return the value
Browse files Browse the repository at this point in the history
Signed-off-by: Jason Hall <[email protected]>
  • Loading branch information
imjasonh committed Jul 3, 2024
1 parent e51a54f commit d5c8afd
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
9 changes: 9 additions & 0 deletions envconfig.go
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,15 @@ func Process(ctx context.Context, i any, mus ...Mutator) error {
})
}

// MustProcess is a helper that calls [Process] and panics if an error is
// encountered. The input value is returned after processing.
func MustProcess[T any](ctx context.Context, i T, mus ...Mutator) T {
if err := Process(ctx, i, mus...); err != nil {
panic(err)
}
return i
}

// ProcessWith executes the decoding process using the provided [Config].
func ProcessWith(ctx context.Context, c *Config) error {
if c == nil {
Expand Down
22 changes: 22 additions & 0 deletions envconfig_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3034,3 +3034,25 @@ func TestValidateEnvName(t *testing.T) {
func ptrTo[T any](i T) *T {
return &i
}

func TestMustProcess_Panic(t *testing.T) {
defer func() {
if r := recover(); r == nil {
t.Error("expected a panic")
}
}()
MustProcess(context.Background(), struct {
Unset string `env:"UNSET" required:"true"`
}{})
}

func TestMustProcess_Value(t *testing.T) {
t.Setenv("SET", "value")
s := MustProcess(context.Background(), &struct {
Set string `env:"SET"`
}{})

if s.Set != "value" {
t.Fatalf("expected %q to be %q", s.Set, "value")
}
}

0 comments on commit d5c8afd

Please sign in to comment.