-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patherrors_test.go
73 lines (58 loc) · 2.33 KB
/
errors_test.go
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
package simba_test
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/sillen102/simba"
"github.com/sillen102/simba/simbaContext"
"gotest.tools/v3/assert"
)
func TestHandleError(t *testing.T) {
t.Parallel()
t.Run("log wrapped error", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/test", nil)
w := httptest.NewRecorder()
logBuffer := &bytes.Buffer{}
logger := slog.New(slog.NewTextHandler(logBuffer, &slog.HandlerOptions{}))
ctx := context.WithValue(req.Context(), simbaContext.LoggerKey, logger)
req = req.WithContext(ctx)
simba.HandleError(w, req, simba.WrapError(
http.StatusInternalServerError,
fmt.Errorf("outermost error: %w", fmt.Errorf("wrapping error: %w", errors.New("original error"))),
"Internal server error"))
assert.Equal(t, http.StatusInternalServerError, w.Code)
assert.Equal(t, "application/json", w.Header().Get("Content-Type"))
var errorResponse simba.ErrorResponse
err := json.NewDecoder(w.Body).Decode(&errorResponse)
assert.NilError(t, err)
assert.Equal(t, http.StatusInternalServerError, errorResponse.Status)
assert.Equal(t, "Internal server error", errorResponse.Message)
expectedLog := "wrapping error: original error"
assert.Assert(t, strings.Contains(logBuffer.String(), expectedLog))
})
t.Run("unauthorized does not show wrapped error", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/test", nil)
w := httptest.NewRecorder()
logBuffer := &bytes.Buffer{}
logger := slog.New(slog.NewTextHandler(logBuffer, &slog.HandlerOptions{}))
ctx := context.WithValue(req.Context(), simbaContext.LoggerKey, logger)
req = req.WithContext(ctx)
simba.HandleError(w, req, simba.WrapError(http.StatusUnauthorized, errors.New("wrapped error"), "Internal server error"))
assert.Equal(t, http.StatusUnauthorized, w.Code)
assert.Equal(t, "application/json", w.Header().Get("Content-Type"))
var errorResponse simba.ErrorResponse
err := json.NewDecoder(w.Body).Decode(&errorResponse)
assert.NilError(t, err)
assert.Equal(t, http.StatusUnauthorized, errorResponse.Status)
assert.Equal(t, "unauthorized", errorResponse.Message) // hide details of the error
expectedLog := "wrapped error"
assert.Assert(t, strings.Contains(logBuffer.String(), expectedLog))
})
}