-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexit.go
More file actions
37 lines (30 loc) · 772 Bytes
/
exit.go
File metadata and controls
37 lines (30 loc) · 772 Bytes
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
package cli
import (
"fmt"
"os"
"os/exec"
"github.com/bobg/errors"
)
// ExitError is an error that causes the program to exit with a given status code.
type ExitError struct {
Code int
}
// Error implements the error interface.
func (e ExitError) Error() string {
return fmt.Sprintf("exit status %d", e.Code)
}
// ExitCode returns an ExitError with the given code.
func ExitCode(code int) *ExitError {
return &ExitError{Code: code}
}
// ExitWithError exits the program with an error.
func ExitWithError(err error) {
fmt.Println(err)
if exitErr := new(ExitError); errors.As(err, &exitErr) {
os.Exit(exitErr.Code)
} else if exitErr := new(exec.ExitError); errors.As(err, &exitErr) {
os.Exit(exitErr.ExitCode())
} else if err != nil {
os.Exit(1)
}
}