/
code.go
63 lines (51 loc) · 1009 Bytes
/
code.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
package exitcode
import (
"errors"
"flag"
"os"
)
// Coder is an interface to control what value Get returns.
type Coder interface {
error
ExitCode() int
}
// Get gets the exit code associated with an error. Cases:
//
// nil or flag.ErrHelp => 0
// errors implementing Coder => value returned by ExitCode
// all other errors => 1
func Get(err error) int {
if err == nil {
return 0
}
if coder := Coder(nil); errors.As(err, &coder) {
return coder.ExitCode()
}
if errors.Is(err, flag.ErrHelp) {
return 0
}
return 1
}
// Set wraps an error in a Coder, setting its error code.
func Set(err error, code int) error {
if err == nil {
return nil
}
return coder{err, code}
}
var _ Coder = coder{}
type coder struct {
error
int
}
func (co coder) ExitCode() int {
return co.int
}
func (co coder) Unwrap() error {
return co.error
}
// Exit is a convenience function that calls os.Exit
// with the exit code associated with err.
func Exit(err error) {
os.Exit(Get(err))
}