-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathhttperror_external_test.go
More file actions
52 lines (41 loc) · 1.04 KB
/
httperror_external_test.go
File metadata and controls
52 lines (41 loc) · 1.04 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
// SPDX-License-Identifier: MIT
// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors
// run tests as external package to get real feel for API
package echo_test
import (
"encoding/json"
"fmt"
"github.com/labstack/echo/v5"
"net/http"
"net/http/httptest"
)
func ExampleDefaultHTTPErrorHandler() {
e := echo.New()
e.GET("/api/endpoint", func(c *echo.Context) error {
return &apiError{
Code: http.StatusBadRequest,
Body: map[string]any{"message": "custom error"},
}
})
req := httptest.NewRequest(http.MethodGet, "/api/endpoint?err=1", nil)
resp := httptest.NewRecorder()
e.ServeHTTP(resp, req)
fmt.Printf("%d %s", resp.Code, resp.Body.String())
// Output: 400 {"error":{"message":"custom error"}}
}
type apiError struct {
Code int
Body any
}
func (e *apiError) StatusCode() int {
return e.Code
}
func (e *apiError) MarshalJSON() ([]byte, error) {
type body struct {
Error any `json:"error"`
}
return json.Marshal(body{Error: e.Body})
}
func (e *apiError) Error() string {
return http.StatusText(e.Code)
}