-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherror_handler_test.go
More file actions
100 lines (85 loc) · 2.58 KB
/
error_handler_test.go
File metadata and controls
100 lines (85 loc) · 2.58 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
93
94
95
96
97
98
99
100
package amaro_test
import (
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"testing"
"github.com/buildwithgo/amaro"
"github.com/buildwithgo/amaro/routers"
)
func TestErrorHandler(t *testing.T) {
// 1. Default Handler (Plain Text)
t.Run("DefaultErrorHandler", func(t *testing.T) {
app := amaro.New(amaro.WithRouter(routers.NewTrieRouter()))
// Force a 404
req := httptest.NewRequest("GET", "/not-found", nil)
w := httptest.NewRecorder()
app.ServeHTTP(w, req)
if w.Code != http.StatusNotFound {
t.Errorf("Expected 404, got %d", w.Code)
}
if w.Body.String() != "method not found\n" && w.Body.String() != "not found\n" {
t.Errorf("Expected 'method not found' or 'not found', got '%s'", w.Body.String())
}
})
// 2. Custom JSON Handler
t.Run("CustomJSONHandler", func(t *testing.T) {
type ErrorResponse struct {
Success bool `json:"success"`
Error string `json:"error"`
Code int `json:"code"`
}
customHandler := func(c *amaro.Context, err error, code int) {
c.Writer.Header().Set("Content-Type", "application/json")
c.Writer.WriteHeader(code)
json.NewEncoder(c.Writer).Encode(ErrorResponse{
Success: false,
Error: err.Error(),
Code: code,
})
}
app := amaro.New(
amaro.WithRouter(routers.NewTrieRouter()),
amaro.WithErrorHandler(customHandler),
)
// Case A: 404 Not Found
t.Run("NotFound", func(t *testing.T) {
req := httptest.NewRequest("GET", "/api/missing", nil)
w := httptest.NewRecorder()
app.ServeHTTP(w, req)
if w.Code != http.StatusNotFound {
t.Errorf("Expected 404, got %d", w.Code)
}
if w.Header().Get("Content-Type") != "application/json" {
t.Errorf("Expected application/json content type")
}
var resp ErrorResponse
if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
t.Fatal(err)
}
if resp.Success != false || resp.Code != 404 {
t.Errorf("Unexpected JSON response: %+v", resp)
}
})
// Case B: 500 Internal Error (via handler error)
app.GET("/panic", func(c *amaro.Context) error {
return errors.New("something went wrong")
})
t.Run("InternalError", func(t *testing.T) {
req := httptest.NewRequest("GET", "/panic", nil)
w := httptest.NewRecorder()
app.ServeHTTP(w, req)
if w.Code != http.StatusInternalServerError {
t.Errorf("Expected 500, got %d", w.Code)
}
var resp ErrorResponse
if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
t.Fatal(err)
}
if resp.Error != "something went wrong" {
t.Errorf("Expected error message 'something went wrong', got '%s'", resp.Error)
}
})
})
}