-
Notifications
You must be signed in to change notification settings - Fork 0
/
errors.go
84 lines (61 loc) · 1.56 KB
/
errors.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
package jrpc
import (
"fmt"
"github.com/goccy/go-json"
)
var (
errorParsingJSONString = []byte(`{"jsonrpc": "2.0", "error": {"code": -32700, "message": "Parse error"}, "id": null}`)
errorInvalidRequest = []byte(`{"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request"}, "id": null}`)
)
type Error struct {
Code int `json:"code"`
Message string `json:"message"`
Data any `json:"data"`
}
func (e *Error) Error() string {
str := fmt.Sprintf(`{"code": %d, "message": "%s"`, e.Code, e.Message)
data := func() string {
if e.Data != nil {
jsonData, err := json.Marshal(e.Data)
if err != nil {
jsonData = []byte("error during marshaling error data: " + err.Error())
}
return fmt.Sprintf(`, "data": %s`, string(jsonData))
}
return ""
}()
str += data
str += "}"
return str
}
func ParseError(msg ...string) *Error {
err := &Error{Code: -32700, Message: "Parse error"}
if len(msg) != 0 {
err.Message = msg[0]
}
return err
}
func InvalidRequestError(msg ...string) *Error {
err := &Error{Code: -32600, Message: "Invalid Request"}
if len(msg) != 0 {
err.Message = msg[0]
}
return err
}
func MethodNotFoundError() *Error {
return &Error{Code: -32601, Message: "Method not found"}
}
func InvalidParamsError(msg ...string) *Error {
err := &Error{Code: -32602, Message: "Invalid params"}
if len(msg) != 0 {
err.Message = msg[0]
}
return err
}
func InternalError(msg ...string) *Error {
err := &Error{Code: -32603, Message: "Internal error"}
if len(msg) != 0 {
err.Message = msg[0]
}
return err
}