@@ -23,6 +23,8 @@ package fx
23
23
import (
24
24
"context"
25
25
"time"
26
+
27
+ "go.uber.org/multierr"
26
28
)
27
29
28
30
// Shutdowner provides a method that can manually trigger the shutdown of the
@@ -34,19 +36,19 @@ type Shutdowner interface {
34
36
}
35
37
36
38
// ShutdownOption provides a way to configure properties of the shutdown
37
- // process. Currently, no options have been implemented.
39
+ // process.
38
40
type ShutdownOption interface {
39
41
apply (* shutdowner )
40
42
}
41
43
42
44
type exitCodeOption int
43
45
46
+ var _ ShutdownOption = exitCodeOption (0 )
47
+
44
48
func (code exitCodeOption ) apply (s * shutdowner ) {
45
49
s .exitCode = int (code )
46
50
}
47
51
48
- var _ ShutdownOption = exitCodeOption (0 )
49
-
50
52
// ExitCode is a [ShutdownOption] that may be passed to the Shutdown method of the
51
53
// [Shutdowner] interface.
52
54
// The given integer exit code will be broadcasted to any receiver waiting
@@ -71,6 +73,41 @@ func ShutdownTimeout(timeout time.Duration) ShutdownOption {
71
73
return shutdownTimeoutOption (timeout )
72
74
}
73
75
76
+ type shutdownErrorOption []error
77
+
78
+ func (errs shutdownErrorOption ) apply (s * shutdowner ) {
79
+ s .app .err = multierr .Append (s .app .err , multierr .Combine (errs ... ))
80
+ }
81
+
82
+ var _ ShutdownOption = shutdownErrorOption ([]error {})
83
+
84
+ // ShutdownError registers any number of errors with the application shutdown.
85
+ // If more than one error is given, the errors are combined into a
86
+ // single error. Similar to invocations, errors are applied in order.
87
+ //
88
+ // You can use these errors, for example, to decide what to do after the app shutdown.
89
+ //
90
+ // customErr := errors.New("something went wrong")
91
+ // app := fx.New(
92
+ // ...
93
+ // fx.Provide(func(s fx.Shutdowner, a A) B {
94
+ // s.Shutdown(fx.ShutdownError(customErr))
95
+ // }),
96
+ // ...
97
+ // )
98
+ // err := app.Start(context.Background())
99
+ // if err != nil {
100
+ // panic(err)
101
+ // }
102
+ // defer app.Stop(context.Background())
103
+ //
104
+ // if err := app.Err(); errors.Is(err, customErr) {
105
+ // // custom logic here
106
+ // }
107
+ func ShutdownError (errs ... error ) ShutdownOption {
108
+ return shutdownErrorOption (errs )
109
+ }
110
+
74
111
type shutdowner struct {
75
112
app * App
76
113
exitCode int
0 commit comments