srv.httpRespondWithError   A
last analyzed

Complexity

Conditions 3

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 8
dl 0
loc 11
c 0
b 0
f 0
rs 10
nop 6
1
package srv
2
3
import (
4
	"encoding/json"
5
	"errors"
6
	"log"
7
	"net/http"
8
	"os"
9
10
	"github.com/cronnoss/tk-api/internal/common/slugerrors"
11
)
12
13
func InternalError(slug string, err error, w http.ResponseWriter, r *http.Request) {
14
	httpRespondWithError(err, slug, w, r, "Internal server error", http.StatusInternalServerError)
15
}
16
17
func Unauthorised(slug string, err error, w http.ResponseWriter, r *http.Request) {
18
	httpRespondWithError(err, slug, w, r, "Unauthorised", http.StatusUnauthorized)
19
}
20
21
func BadRequest(slug string, err error, w http.ResponseWriter, r *http.Request) {
22
	httpRespondWithError(err, slug, w, r, "Bad request", http.StatusBadRequest)
23
}
24
25
func NotFound(slug string, err error, w http.ResponseWriter, r *http.Request) {
26
	httpRespondWithError(err, slug, w, r, "Not found", http.StatusBadRequest)
27
}
28
29
func RespondWithError(err error, w http.ResponseWriter, r *http.Request) {
30
	var slugError slugerrors.SlugError
31
	if !errors.As(err, &slugError) {
32
		InternalError("internal-server-error", err, w, r)
33
		return
34
	}
35
36
	switch slugError.ErrorType() {
37
	case slugerrors.ErrorTypeAuthorization:
38
		Unauthorised(slugError.Slug(), slugError, w, r)
39
	case slugerrors.ErrorTypeBadRequest:
40
		BadRequest(slugError.Slug(), slugError, w, r)
41
	case slugerrors.ErrorTypeNotFound:
42
		NotFound(slugError.Slug(), slugError, w, r)
43
	default:
44
		InternalError(slugError.Slug(), slugError, w, r)
45
	}
46
}
47
48
func httpRespondWithError(err error, slug string, w http.ResponseWriter, _ *http.Request, msg string, status int) {
49
	log.Printf("error: %s, slug: %s, msg: %s", err, slug, msg)
50
51
	resp := ErrorResponse{Slug: slug, httpStatus: status}
52
	if os.Getenv("DEBUG_ERRORS") != "" && err != nil {
53
		resp.Error = err.Error()
54
	}
55
56
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
57
	w.WriteHeader(status)
58
	_ = json.NewEncoder(w).Encode(resp)
59
}
60
61
type ErrorResponse struct {
62
	Slug       string `json:"slug"`
63
	Error      string `json:"error,omitempty"`
64
	httpStatus int
65
}
66
67
func (e ErrorResponse) Render(w http.ResponseWriter, _ *http.Request) error {
68
	w.WriteHeader(e.httpStatus)
69
	return nil
70
}
71