-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
exitcode.go
80 lines (67 loc) · 1.85 KB
/
exitcode.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// Copyright (c) 2020, Roel Schut. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package errors
import (
"fmt"
)
// ExitCoder interfaces provide access to an exit code.
type ExitCoder interface {
error
ExitCode() int
}
// ExitCoderSetter interfaces provide access to an exit code which can be
// changed.
type ExitCoderSetter interface {
ExitCoder
SetExitCode(int)
}
// WithExitCode adds an exit status code to the error which may indicate a
// fatal error. The exit code can be supplied to os.Exit to terminate the
// program immediately.
func WithExitCode(err error, exitCode int) ExitCoder {
if err == nil {
return nil
}
//goland:noinspection GoTypeAssertionOnErrors
if e, ok := err.(ExitCoderSetter); ok {
e.SetExitCode(exitCode)
return e
}
return &exitCodeError{
embedError: &embedError{error: err},
exitCode: exitCode,
}
}
// GetExitCode returns an exit status code if the error implements the
// ExitCoder interface. If not, it returns 0.
func GetExitCode(err error) int { return GetExitCodeOr(err, 0) }
// GetExitCodeOr returns the exit status code from the first found ExitCoder
// in err's error chain. If none is found, it returns the provided value or.
func GetExitCodeOr(err error, or int) int {
for {
//goland:noinspection GoTypeAssertionOnErrors
if e, ok := err.(ExitCoder); ok {
return e.ExitCode()
}
err = Unwrap(err)
if err == nil {
break
}
}
return or
}
type exitCodeError struct {
*embedError
exitCode int
}
func (e *exitCodeError) SetExitCode(c int) { e.exitCode = c }
func (e *exitCodeError) ExitCode() int { return e.exitCode }
// GoString prints the error in basic Go syntax.
func (e *exitCodeError) GoString() string {
return fmt.Sprintf(
"errors.exitCodeError{exitCode: %d, embedErr: %#v}",
e.exitCode,
e.error,
)
}