Repository navigation
Expand file tree
/
Copy patherrors.go
More file actions
92 lines (79 loc) · 2.54 KB
/
Copy patherrors.go
File metadata and controls
92 lines (79 loc) · 2.54 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
83
84
85
86
87
88
89
90
91
92
package web
import (
"fmt"
"net/http"
"go.starlark.net/starlark"
)
// ErrorResponse represents a standardized error response.
// This structure provides a consistent format for all HTTP error responses
// throughout the web module, including error message, HTTP status code, and description.
type ErrorResponse struct {
Error string `json:"error"`
Message string `json:"message,omitempty"`
Code int `json:"code"`
}
// ErrorHandler represents a custom error handler function
type ErrorHandler struct {
statusCodes []int
handler starlark.Callable
}
// ErrorHandlerRegistry manages custom error handlers
type ErrorHandlerRegistry struct {
handlers map[int]starlark.Callable
}
// NewErrorHandlerRegistry creates a new error handler registry
func NewErrorHandlerRegistry() *ErrorHandlerRegistry {
return &ErrorHandlerRegistry{
handlers: make(map[int]starlark.Callable),
}
}
// RegisterHandler registers an error handler for specific status codes
func (ehr *ErrorHandlerRegistry) RegisterHandler(statusCodes []int, handler starlark.Callable) {
for _, code := range statusCodes {
ehr.handlers[code] = handler
}
}
// GetHandler returns the handler for a specific status code
func (ehr *ErrorHandlerRegistry) GetHandler(statusCode int) starlark.Callable {
return ehr.handlers[statusCode]
}
// HandleError calls the appropriate error handler or returns a default error response
func (ehr *ErrorHandlerRegistry) HandleError(statusCode int, req *Request) *Response {
handler := ehr.GetHandler(statusCode)
if handler == nil {
// Return default error response
return &Response{
StatusCode: statusCode,
Headers: map[string]string{
"Content-Type": MIMEApplicationJSON,
},
Body: fmt.Sprintf(`{"error":%q,"code":%d}`, http.StatusText(statusCode), statusCode),
}
}
thread := &starlark.Thread{Name: "error_handler"}
reqWrapper := NewRequestWrapper(req)
args := starlark.Tuple{reqWrapper}
result, err := starlark.Call(thread, handler, args, nil)
if err != nil {
// If error handler fails, return default error
return &Response{
StatusCode: 500,
Headers: map[string]string{
"Content-Type": MIMEApplicationJSON,
},
Body: fmt.Sprintf(`{"error":"Error handler failed: %s"}`, err.Error()),
}
}
// Convert result to Response
if respWrapper, ok := result.(*ResponseWrapper); ok {
return respWrapper.response
}
// If not a response wrapper, return error
return &Response{
StatusCode: 500,
Headers: map[string]string{
"Content-Type": MIMEApplicationJSON,
},
Body: `{"error":"Error handler must return a response"}`,
}
}