This repository has been archived by the owner on Apr 24, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
/
error.go
72 lines (60 loc) · 1.45 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
package cmdkit
import (
"encoding/json"
"errors"
"fmt"
)
// ErrorType signfies a category of errors
type ErrorType uint
// ErrorTypes convey what category of error ocurred
const (
ErrNormal ErrorType = iota // general errors
ErrClient // error was caused by the client, (e.g. invalid CLI usage)
ErrImplementation // programmer error in the server
ErrNotFound // == HTTP 404
ErrFatal // abort instantly
// TODO: add more types of errors for better error-specific handling
)
// Error is a struct for marshalling errors
type Error struct {
Message string
Code ErrorType
}
// Errorf returns an Error with the given code and format specification
func Errorf(code ErrorType, format string, args ...interface{}) Error {
return Error{
Code: code,
Message: fmt.Sprintf(format, args...),
}
}
func (e Error) Error() string {
return e.Message
}
func (e Error) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Message string
Code ErrorType
Type string
}{
Message: e.Message,
Code: e.Code,
Type: "error",
})
}
func (e *Error) UnmarshalJSON(data []byte) error {
var w struct {
Message string
Code ErrorType
Type string
}
err := json.Unmarshal(data, &w)
if err != nil {
return err
}
if w.Type != "error" {
return errors.New("not of type error")
}
e.Message = w.Message
e.Code = w.Code
return nil
}