-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherrors.go
More file actions
72 lines (63 loc) · 1.85 KB
/
errors.go
File metadata and controls
72 lines (63 loc) · 1.85 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
package hostlib
import (
"encoding/json"
)
// ErrorResponse represents a structured error that can be returned as JSON to plugins.
// This ensures plugins receive consistent, parseable errors instead of causing WASM traps.
type ErrorResponse struct {
// Error is a machine-readable error type identifier (e.g., "VALIDATION_ERROR", "INTERNAL_ERROR").
Error string `json:"error"`
// Message is a human-readable error description.
Message string `json:"message"`
// Code is a numeric error code (e.g., 400, 500).
Code int `json:"code"`
}
// ToJSON serializes the ErrorResponse to JSON bytes.
// Returns nil if serialization fails (which should never happen for this simple type).
func (e ErrorResponse) ToJSON() []byte {
data, err := json.Marshal(e)
if err != nil {
return nil
}
return data
}
// NewValidationError creates an error response for bad input (e.g., malformed JSON).
func NewValidationError(message string) ErrorResponse {
return ErrorResponse{
Error: "VALIDATION_ERROR",
Message: message,
Code: 400,
}
}
// NewNotFoundError creates an error response for unknown handler names.
func NewNotFoundError(name string) ErrorResponse {
return ErrorResponse{
Error: "NOT_FOUND",
Message: "unknown host function: " + name,
Code: 404,
}
}
// NewInternalError creates an error response for unexpected failures.
func NewInternalError(message string) ErrorResponse {
return ErrorResponse{
Error: "INTERNAL_ERROR",
Message: message,
Code: 500,
}
}
// NewPanicError creates an error response for recovered panics.
func NewPanicError(panicValue any) ErrorResponse {
var msg string
if err, ok := panicValue.(error); ok {
msg = err.Error()
} else if s, ok := panicValue.(string); ok {
msg = s
} else {
msg = "panic recovered"
}
return ErrorResponse{
Error: "INTERNAL_ERROR",
Message: "panic: " + msg,
Code: 500,
}
}