Skip to content

Commit

Permalink
caddyfile: Errf enable error chain unwrapping
Browse files Browse the repository at this point in the history
  • Loading branch information
ggicci committed Jul 17, 2021
1 parent 124ba1b commit b4efccc
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
19 changes: 16 additions & 3 deletions caddyconfig/caddyfile/dispenser.go
Original file line number Diff line number Diff line change
Expand Up @@ -343,15 +343,28 @@ func (d *Dispenser) EOFErr() error {
return d.Errf("Unexpected EOF")
}

type parseError struct {
file string
line int
innerError error
}

func (e parseError) Error() string {
return fmt.Sprintf("%s:%d - Error during parsing: %s", e.file, e.line, e.innerError.Error())
}

func (e parseError) Unwrap() error {
return e.innerError
}

// Err generates a custom parse-time error with a message of msg.
func (d *Dispenser) Err(msg string) error {
msg = fmt.Sprintf("%s:%d - Error during parsing: %s", d.File(), d.Line(), msg)
return errors.New(msg)
return parseError{d.File(), d.Line(), errors.New(msg)}
}

// Errf is like Err, but for formatted error messages
func (d *Dispenser) Errf(format string, args ...interface{}) error {
return d.Err(fmt.Sprintf(format, args...))
return parseError{d.File(), d.Line(), fmt.Errorf(format, args...)}
}

// Delete deletes the current token and returns the updated slice
Expand Down
7 changes: 7 additions & 0 deletions caddyconfig/caddyfile/dispenser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package caddyfile

import (
"errors"
"reflect"
"strings"
"testing"
Expand Down Expand Up @@ -303,4 +304,10 @@ func TestDispenser_ArgErr_Err(t *testing.T) {
if !strings.Contains(err.Error(), "foobar") {
t.Errorf("Expected error message with custom message in it ('foobar'); got '%v'", err)
}

var ErrBarIsFull = errors.New("bar is full")
bookingError := d.Errf("unable to reserve: %w", ErrBarIsFull)
if !errors.Is(bookingError, ErrBarIsFull) {
t.Errorf("Errf(): should be able to unwrap the error chain")
}
}

0 comments on commit b4efccc

Please sign in to comment.