Better errors
This commit is contained in:
parent
262768e3a2
commit
c74596c6a6
3 changed files with 14 additions and 4 deletions
|
@ -50,7 +50,7 @@ func (e Error) Error() string {
|
||||||
return fmt.Sprintf("jsonrpc2 error: code: %d message: %s", e.Code, e.Message)
|
return fmt.Sprintf("jsonrpc2 error: code: %d message: %s", e.Code, e.Message)
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewError(code int) Error {
|
func ErrorFromCode(code int) Error {
|
||||||
if _, ok := errorMap[code]; ok {
|
if _, ok := errorMap[code]; ok {
|
||||||
return Error{
|
return Error{
|
||||||
Code: code,
|
Code: code,
|
||||||
|
@ -59,3 +59,13 @@ func NewError(code int) Error {
|
||||||
}
|
}
|
||||||
return Error{Code: code}
|
return Error{Code: code}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func NewError(message string, code int) Error {
|
||||||
|
if code == 0 {
|
||||||
|
code = ErrUser
|
||||||
|
}
|
||||||
|
return Error{
|
||||||
|
Code: code,
|
||||||
|
Message: message,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -114,7 +114,7 @@ func (r *RpcServer) callMethod(ctx context.Context, req *rpcRequest) *rpcRespons
|
||||||
if !ok {
|
if !ok {
|
||||||
return &rpcResponse{
|
return &rpcResponse{
|
||||||
Jsonrpc: version,
|
Jsonrpc: version,
|
||||||
Error: NewError(ErrCodeMethodNotFound),
|
Error: ErrorFromCode(ErrCodeMethodNotFound),
|
||||||
Id: req.Id,
|
Id: req.Id,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -137,7 +137,7 @@ func (r *RpcServer) callMethod(ctx context.Context, req *rpcRequest) *rpcRespons
|
||||||
func WriteError(code int, enc *json.Encoder) {
|
func WriteError(code int, enc *json.Encoder) {
|
||||||
enc.Encode(rpcResponse{
|
enc.Encode(rpcResponse{
|
||||||
Jsonrpc: version,
|
Jsonrpc: version,
|
||||||
Error: NewError(code),
|
Error: ErrorFromCode(code),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -28,7 +28,7 @@ func H[RQ any, RS any](handler func(context.Context, *RQ) (RS, error)) Handler {
|
||||||
return func(ctx context.Context, in json.RawMessage) (json.RawMessage, error) {
|
return func(ctx context.Context, in json.RawMessage) (json.RawMessage, error) {
|
||||||
req := new(RQ)
|
req := new(RQ)
|
||||||
if err := json.Unmarshal(in, req); err != nil {
|
if err := json.Unmarshal(in, req); err != nil {
|
||||||
return nil, NewError(ErrCodeParseError)
|
return nil, ErrorFromCode(ErrCodeParseError)
|
||||||
}
|
}
|
||||||
resp, err := handler(ctx, req)
|
resp, err := handler(ctx, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
Loading…
Reference in a new issue