-
Notifications
You must be signed in to change notification settings - Fork 0
/
errors.go
46 lines (39 loc) · 1.18 KB
/
errors.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
package http
import (
"context"
"encoding/json"
"net/http"
"strings"
"github.com/AraiYuno/golang-rest-api/internal/core/errors"
"github.com/AraiYuno/golang-rest-api/internal/core/logging"
"go.uber.org/zap"
)
func handleError(ctx context.Context, w http.ResponseWriter, err error) {
logging.From(ctx).Error("error occurred in request", zap.Error(err))
switch {
case errors.Is(err, errors.ErrInvalidRequest):
fallthrough
case errors.Is(err, errors.ErrValidation):
w.WriteHeader(http.StatusBadRequest)
case errors.Is(err, errors.ErrNotFound):
w.WriteHeader(http.StatusNotFound)
case errors.Is(err, errors.ErrUnknown):
fallthrough
default:
w.WriteHeader(http.StatusInternalServerError)
}
errJSON := struct {
Error string `json:"error"`
}{
Error: strings.Split(err.Error(), errors.ErrSeperator)[0], // TODO we may need to strip additional error information
}
data, err := json.Marshal(errJSON)
if err != nil {
logging.From(ctx).Error("failed to serialize error response", zap.Error(err))
data = []byte(`{"error": "internal server error"}`)
}
_, err = w.Write(data)
if err != nil {
logging.From(ctx).Error("failed to write error response", zap.Error(err))
}
}