82 lines
1.7 KiB
Go
82 lines
1.7 KiB
Go
package server
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
|
|
grpcCodes "google.golang.org/grpc/codes"
|
|
grpcStatus "google.golang.org/grpc/status"
|
|
)
|
|
|
|
type ErrorCode int
|
|
|
|
const (
|
|
E_PARSE ErrorCode = -32700
|
|
E_INVALID_REQ ErrorCode = -32600
|
|
E_NOT_FOUND_METHOD ErrorCode = -32601
|
|
E_INVALID_PARAMS ErrorCode = -32602
|
|
E_INTERNAL ErrorCode = -32603
|
|
// -32000 ~ -32099
|
|
E_SERVER ErrorCode = -32000
|
|
)
|
|
|
|
var ErrNullResult = errors.New("result is null")
|
|
|
|
type Error struct {
|
|
Code ErrorCode `json:"code"`
|
|
Message string `json:"message"`
|
|
Data interface{} `json:"data,omitempty"`
|
|
}
|
|
|
|
// Request is protocol which Websocket Request
|
|
type Request struct {
|
|
Protocol string `json:"protocol"`
|
|
Method string `json:"method"`
|
|
Params []string `json:"params,omitempty"`
|
|
ID *json.RawMessage `json:"id,omitempty"`
|
|
}
|
|
|
|
// Response is protocol which Websocket Response
|
|
type Response struct {
|
|
Protocol string `json:"protocol"`
|
|
Result *string `json:"result,omitempty"`
|
|
Error *Error `json:"error,omitempty"`
|
|
ID *json.RawMessage `json:"id,omitempty"`
|
|
}
|
|
|
|
func NewError(code ErrorCode, err error, data interface{}) *Error {
|
|
e := &Error{
|
|
Code: code,
|
|
Message: err.Error(),
|
|
Data: data,
|
|
}
|
|
return e
|
|
}
|
|
|
|
func NewGrpcError(err error) *Error {
|
|
resultStatus, ok := grpcStatus.FromError(err)
|
|
if !ok {
|
|
return nil
|
|
}
|
|
|
|
var code ErrorCode
|
|
|
|
switch resultStatus.Code() {
|
|
case grpcCodes.InvalidArgument:
|
|
code = E_INVALID_PARAMS
|
|
case grpcCodes.Internal:
|
|
code = E_INTERNAL
|
|
case grpcCodes.Unimplemented:
|
|
code = E_NOT_FOUND_METHOD
|
|
default:
|
|
code = E_SERVER
|
|
}
|
|
|
|
e := &Error{
|
|
Code: code,
|
|
Message: resultStatus.Message(),
|
|
Data: nil,
|
|
}
|
|
return e
|
|
}
|