Skip to content

Commit e3ccfb4

Browse files
committed
feat: enhance error handling with custom HTTP error types
1 parent 5ad026c commit e3ccfb4

File tree

1 file changed

+55
-14
lines changed

1 file changed

+55
-14
lines changed

utils/costum_error.go

Lines changed: 55 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,47 @@
11
package utils
22

33
import (
4+
"net/http"
45
"strings"
56

67
"github.com/hammer-code/lms-be/domain"
78
)
89

9-
func CheckError(err, sub, message string, code int) (domain.HttpResponse, bool) {
10+
type CustomHttpError struct {
11+
Code int
12+
Message string
13+
OriginError error
14+
}
15+
16+
func (e *CustomHttpError) Error() string {
17+
return e.Message
18+
}
19+
20+
func NewBadRequestError(msg string, err error) *CustomHttpError {
21+
return &CustomHttpError{
22+
Code: http.StatusBadRequest,
23+
Message: msg,
24+
OriginError: err,
25+
}
26+
}
27+
28+
func NewUnauthorizedError(msg string, err error) *CustomHttpError {
29+
return &CustomHttpError{
30+
Code: http.StatusUnauthorized,
31+
Message: msg,
32+
OriginError: err,
33+
}
34+
}
35+
36+
func NewInternalServerError(err error) *CustomHttpError {
37+
return &CustomHttpError{
38+
Code: http.StatusInternalServerError,
39+
Message: "Internal server error",
40+
OriginError: err,
41+
}
42+
}
1043

44+
func CheckError(err, sub, message string, code int) (domain.HttpResponse, bool) {
1145
if strings.Contains(err, sub) {
1246
return domain.HttpResponse{
1347
Code: code,
@@ -17,25 +51,32 @@ func CheckError(err, sub, message string, code int) (domain.HttpResponse, bool)
1751
return domain.HttpResponse{}, false
1852
}
1953

20-
func CostumErr(err string) domain.HttpResponse {
54+
func CustomErrorResponse(err error) domain.HttpResponse {
55+
if customErr, ok := err.(*CustomHttpError); ok {
56+
errStr := customErr.OriginError.Error()
57+
resp, ok := CheckError(errStr, "\"uni_users_email\" (SQLSTATE 23505)", "User already exist", 400)
58+
if ok {
59+
return resp
60+
}
2161

22-
resp, ok := CheckError(err, "\"uni_users_email\" (SQLSTATE 23505)", "User already exist", 400)
23-
if ok {
24-
return resp
25-
}
62+
resp, ok = CheckError(errStr, "\"uni_logout_token\" (SQLSTATE 23505)", "You have already logged out.", 400)
63+
if ok {
64+
return resp
65+
}
2666

27-
resp, ok = CheckError(err, "\"uni_logout_token\" (SQLSTATE 23505)", "You have already logged out.", 400)
28-
if ok {
29-
return resp
30-
}
67+
resp, ok = CheckError(errStr, "password", "Sorry, your password is incorrect", 400)
68+
if ok {
69+
return resp
70+
}
3171

32-
resp, ok = CheckError(err, "password", "Sorry, your password is incorrect", 400)
33-
if ok {
34-
return resp
72+
return domain.HttpResponse{
73+
Code: customErr.Code,
74+
Message: customErr.Message,
75+
}
3576
}
3677

3778
return domain.HttpResponse{
38-
Code: 400,
79+
Code: http.StatusInternalServerError,
3980
Message: "Internal server error",
4081
}
4182

0 commit comments

Comments
 (0)