-
Notifications
You must be signed in to change notification settings - Fork 0
/
exit_code.go
49 lines (40 loc) · 1.25 KB
/
exit_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
package errext
import (
"errors"
"github.com/gesemaya/k6/errext/exitcodes"
)
// ExitCode is the code with which the application should exit if this error
// bubbles up to the top of the scope. Values should be between 0 and 125:
// https://unix.stackexchange.com/questions/418784/what-is-the-min-and-max-values-of-exit-codes-in-linux
// HasExitCode is a wrapper around an error with an attached exit code.
type HasExitCode interface {
error
ExitCode() exitcodes.ExitCode
}
// WithExitCodeIfNone can attach an exit code to the given error, if it doesn't
// have one already. It won't do anything if the error already had an exit code
// attached. Similarly, if there is no error (i.e. the given error is nil), it
// also won't do anything.
func WithExitCodeIfNone(err error, exitCode exitcodes.ExitCode) error {
if err == nil {
// No error, do nothing
return nil
}
var ecerr HasExitCode
if errors.As(err, &ecerr) {
// The given error already has an exit code, do nothing
return err
}
return withExitCode{err, exitCode}
}
type withExitCode struct {
error
exitCode exitcodes.ExitCode
}
func (wh withExitCode) Unwrap() error {
return wh.error
}
func (wh withExitCode) ExitCode() exitcodes.ExitCode {
return wh.exitCode
}
var _ HasExitCode = withExitCode{}