-
Notifications
You must be signed in to change notification settings - Fork 0
/
code.go
78 lines (60 loc) · 1.7 KB
/
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
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
// Copyright 2020 Lingfei Kong <colin404@foxmail.com>. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package code
import (
"net/http"
"github.com/bolo-tourism/go/pkg/errors"
"github.com/novalagung/gubrak"
)
// ErrCode implements `github.com/marmotedu/errors`.Coder interface.
type ErrCode struct {
// C refers to the code of the ErrCode.
C int
// HTTP status that should be used for the associated error code.
HTTP int
// External (user) facing error text.
Ext string
// Ref specify the reference document.
Ref string
}
var _ errors.Coder = &ErrCode{}
// Code returns the integer code of ErrCode.
func (coder ErrCode) Code() int {
return coder.C
}
// String implements stringer. String returns the external error message,
// if any.
func (coder ErrCode) String() string {
return coder.Ext
}
// Reference returns the reference document.
func (coder ErrCode) Reference() string {
return coder.Ref
}
// HTTPStatus returns the associated HTTP status code, if any. Otherwise,
// returns 200.
func (coder ErrCode) HTTPStatus() int {
if coder.HTTP == 0 {
return http.StatusInternalServerError
}
return coder.HTTP
}
// nolint: unparam
func register(code int, httpStatus int, message string, refs ...string) {
found, _ := gubrak.Includes([]int{200, 400, 401, 403, 404, 500}, httpStatus)
if !found {
panic("http code not in `200, 400, 401, 403, 404, 500`")
}
var reference string
if len(refs) > 0 {
reference = refs[0]
}
coder := &ErrCode{
C: code,
HTTP: httpStatus,
Ext: message,
Ref: reference,
}
errors.MustRegister(coder)
}