-
Notifications
You must be signed in to change notification settings - Fork 18
/
error.go
93 lines (82 loc) · 2.39 KB
/
error.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
81
82
83
84
85
86
87
88
89
90
91
92
93
// Copyright 2013 Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package getopt
import "fmt"
// An Error is returned by Getopt when it encounters an error.
type Error struct {
ErrorCode // General reason of failure.
Err error // The actual error.
Parameter string // Parameter passed to option, if any
Name string // Option that cause error, if any
}
// Error returns the error message, implementing the error interface.
func (i *Error) Error() string { return i.Err.Error() }
// An ErrorCode indicates what sort of error was encountered.
type ErrorCode int
const (
NoError = ErrorCode(iota)
UnknownOption // an invalid option was encountered
MissingParameter // the options parameter is missing
ExtraParameter // a value was set to a long flag
Invalid // attempt to set an invalid value
)
func (e ErrorCode) String() string {
switch e {
case UnknownOption:
return "unknow option"
case MissingParameter:
return "missing argument"
case ExtraParameter:
return "unxpected value"
case Invalid:
return "error setting value"
}
return "unknown error"
}
// unknownOption returns an Error indicating an unknown option was
// encountered.
func unknownOption(name interface{}) *Error {
i := &Error{ErrorCode: UnknownOption}
switch n := name.(type) {
case rune:
if n == '-' {
i.Name = "-"
} else {
i.Name = "-" + string(n)
}
case string:
i.Name = "--" + n
}
i.Err = fmt.Errorf("unknown option: %s", i.Name)
return i
}
// missingArg returns an Error inidicating option o was not passed
// a required paramter.
func missingArg(o Option) *Error {
return &Error{
ErrorCode: MissingParameter,
Name: o.Name(),
Err: fmt.Errorf("missing parameter for %s", o.Name()),
}
}
// extraArg returns an Error inidicating option o was passed the
// unexpected paramter value.
func extraArg(o Option, value string) *Error {
return &Error{
ErrorCode: ExtraParameter,
Name: o.Name(),
Parameter: value,
Err: fmt.Errorf("unexpected parameter passed to %s: %q", o.Name(), value),
}
}
// setError returns an Error inidicating option o and the specified
// error while setting it to value.
func setError(o Option, value string, err error) *Error {
return &Error{
ErrorCode: Invalid,
Name: o.Name(),
Parameter: value,
Err: err,
}
}