generated from dogmatiq/template-go
/
construct.go
65 lines (56 loc) 路 1.53 KB
/
construct.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package imbue
import (
"context"
"fmt"
)
// constructor is a wrapper around a function that constructs a value of type T.
//
// It implements the userFunction interface.
type constructor[T any] struct {
// impl is the constructor implementation. It is typically a closure
// generated by the WithX() functions. It wraps the user-provided
// constructor function to provide a common signature.
impl func(Context) (T, error)
// loc is the location of the code that provided the constructor.
loc location
// rawErr, if true, indicates that Call() should return the error exactly as
// it is returned by the constructor implementation, without wrapping it to
// provide additional context.
rawErr bool
}
// Call invokes the constructor and returns the constructed value.
func (c constructor[T]) Call(ctx context.Context, defers *deferSet) (T, error) {
v, err := c.impl(
&scopedContext{
Context: ctx,
scope: c,
defers: defers,
},
)
if err != nil {
if c.rawErr {
return v, err
}
return v, fmt.Errorf(
"%s failed: %w",
c,
err,
)
}
return v, nil
}
// Location returns the location of the code that provided the constructor.
//
// This is typically the location of the call to the WithX() function, not the
// constructor implementation function definition.
func (c constructor[T]) Location() location {
return c.loc
}
// String returns a description of the constructor for use in error messages.
func (c constructor[T]) String() string {
return fmt.Sprintf(
"%s constructor (%s)",
typeOf[T](),
c.loc,
)
}