-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy patherrors.go
More file actions
82 lines (71 loc) · 2.27 KB
/
errors.go
File metadata and controls
82 lines (71 loc) · 2.27 KB
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
package acp
import (
"context"
"encoding/json"
"errors"
"fmt"
)
// RequestError represents a JSON-RPC error response.
type RequestError struct {
Code int `json:"code"`
Message string `json:"message"`
Data any `json:"data,omitempty"`
}
func (e *RequestError) Error() string {
// Prefer a structured, JSON-style string so callers get details by default
// similar to the TypeScript client.
// Example: {"code":-32603,"message":"Internal error","data":{"details":"..."}}
if e == nil {
return "<nil>"
}
// Try to pretty-print compact JSON for stability in logs.
type view struct {
Code int `json:"code"`
Message string `json:"message"`
Data any `json:"data,omitempty"`
}
v := view{Code: e.Code, Message: e.Message, Data: e.Data}
b, err := json.Marshal(v)
if err == nil {
return string(b)
}
// Fallback if marshal fails.
if e.Data != nil {
return fmt.Sprintf("code %d: %s (data: %v)", e.Code, e.Message, e.Data)
}
return fmt.Sprintf("code %d: %s", e.Code, e.Message)
}
func NewParseError(data any) *RequestError {
return &RequestError{Code: -32700, Message: "Parse error", Data: data}
}
func NewInvalidRequest(data any) *RequestError {
return &RequestError{Code: -32600, Message: "Invalid request", Data: data}
}
func NewMethodNotFound(method string) *RequestError {
return &RequestError{Code: -32601, Message: "Method not found", Data: map[string]any{"method": method}}
}
func NewInvalidParams(data any) *RequestError {
return &RequestError{Code: -32602, Message: "Invalid params", Data: data}
}
func NewInternalError(data any) *RequestError {
return &RequestError{Code: -32603, Message: "Internal error", Data: data}
}
func NewRequestCancelled(data any) *RequestError {
return &RequestError{Code: -32800, Message: "Request cancelled", Data: data}
}
func NewAuthRequired(data any) *RequestError {
return &RequestError{Code: -32000, Message: "Authentication required", Data: data}
}
// toReqErr coerces arbitrary errors into JSON-RPC RequestError.
func toReqErr(err error) *RequestError {
if err == nil {
return nil
}
if re, ok := err.(*RequestError); ok {
return re
}
if errors.Is(err, context.Canceled) {
return NewRequestCancelled(map[string]any{"error": err.Error()})
}
return NewInternalError(map[string]any{"error": err.Error()})
}