aboutsummaryrefslogtreecommitdiff
path: root/rpc/errors.go
blob: e6d7be04a3b8cd1b7e5258efa6cbc64a5047e12c (plain) (blame)
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
//Package rpc provides abstract rpc server
//
//Copyright (C) 2022 Alexander Kiryukhin <i@neonxp.dev>
//
//This file is part of go.neonxp.ru/jsonrpc2 project.
//
//This program is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program.  If not, see <https://www.gnu.org/licenses/>.

package rpc

import "fmt"

const (
	ErrCodeParseError     = -32700
	ErrCodeInvalidRequest = -32600
	ErrCodeMethodNotFound = -32601
	ErrCodeInvalidParams  = -32602
	ErrCodeInternalError  = -32603
	ErrUser               = -32000
)

var errorMap = map[int]string{
	ErrCodeParseError:     "Parse error",      // Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.
	ErrCodeInvalidRequest: "Invalid Request",  // The JSON sent is not a valid Request object.
	ErrCodeMethodNotFound: "Method not found", // The method does not exist / is not available.
	ErrCodeInvalidParams:  "Invalid params",   // Invalid method parameter(s).
	ErrCodeInternalError:  "Internal error",   // Internal JSON-RPC error.
	ErrUser:               "Other error",
}

//-32000 to -32099 	RpcServer error 	Reserved for implementation-defined server-errors.

type Error struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

func (e Error) Error() string {
	return fmt.Sprintf("jsonrpc2 error: code: %d message: %s", e.Code, e.Message)
}

func ErrorFromCode(code int) Error {
	if _, ok := errorMap[code]; ok {
		return Error{
			Code:    code,
			Message: errorMap[code],
		}
	}
	return Error{Code: code}
}

func NewError(message string, code int) Error {
	if code == 0 {
		code = ErrUser
	}
	return Error{
		Code:    code,
		Message: message,
	}
}