Skip to content

Commit ba9c16f

Browse files
feat: SendError helper
1 parent 29f3163 commit ba9c16f

File tree

3 files changed

+19
-1
lines changed

3 files changed

+19
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ Update your existing handler signatures, by adding an `error` return type and ut
2222
func addProduct(w http.ResponseWriter, r *http.Request) error {
2323
var p product
2424
if err := errhandler.ParseJSON(r, &p); err != nil {
25-
return fmt.Errorf("parsing request json: %w", err)
25+
return SendError(w, http.StatusUnprocessableEntity, err)
2626
}
2727

2828
products[p.ID] = p

errhandler.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,16 @@ func SendString(w http.ResponseWriter, message string) error {
3737
return nil
3838
}
3939

40+
// SendError returns an error response to the caller, or fails with an error.
41+
func SendError(w http.ResponseWriter, code int, err error) error {
42+
w.Header().Set("Content-Type", "text/plain")
43+
w.WriteHeader(code)
44+
if _, err := w.Write([]byte(err.Error())); err != nil {
45+
return err
46+
}
47+
return nil
48+
}
49+
4050
// ParseJSON can be used to parse a string from the body of a request.
4151
func ParseJSON(r *http.Request, val any) error {
4252
return json.NewDecoder(r.Body).Decode(val)

errhandler_test.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,14 @@ func TestWrap_ServeHTTP(t *testing.T) {
5757
expectedStatus: http.StatusOK,
5858
expectedBody: "{\"a\":1}\n",
5959
},
60+
{
61+
name: "send error",
62+
handler: Wrap(func(w http.ResponseWriter, r *http.Request) error {
63+
return SendError(w, http.StatusUnprocessableEntity, fmt.Errorf("error doing stuff: %w", errors.New("database error")))
64+
}),
65+
expectedStatus: http.StatusUnprocessableEntity,
66+
expectedBody: "error doing stuff: database error",
67+
},
6068
{
6169
name: "error",
6270
handler: Wrap(func(w http.ResponseWriter, r *http.Request) error {

0 commit comments

Comments
 (0)