forked from focks/apibuildr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patherrorHandler.go
44 lines (39 loc) · 1.08 KB
/
errorHandler.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
package apibuildr
import (
"context"
"encoding/json"
"fmt"
"net/http"
)
func HandleError(ctx context.Context, w http.ResponseWriter, err error) {
foul, ok := err.(*ApiFoul)
if !ok {
HandleInternalError(ctx, w, err)
return
}
handleApiError(ctx, w, foul)
}
func handleApiError(ctx context.Context, w http.ResponseWriter, err *ApiFoul) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(err.StatusCode)
err.RequestId = GetRequestID(ctx)
err.ApiName = GetApiName(ctx)
payload, _ := json.Marshal(err)
if _, er := w.Write(payload); er != nil {
fmt.Println("something went wrong in the server")
}
}
func HandleInternalError(ctx context.Context, w http.ResponseWriter, err error) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
e := ApiFoul{
Message: "something went wrong in the server.",
RequestId: GetRequestID(ctx),
StatusCode: http.StatusInternalServerError,
ApiName: GetApiName(ctx),
}
payload, _ := json.Marshal(e)
if _, er := w.Write(payload); er != nil {
fmt.Println(er.Error())
}
}