Skip to content

Commit 41da9fd

Browse files
committed
fix: refactor error handling in CustomErrorResponse for improved clarity and consistency
1 parent 0d36606 commit 41da9fd

File tree

1 file changed

+20
-6
lines changed

1 file changed

+20
-6
lines changed

utils/costum_error.go

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,29 @@
11
package utils
22

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

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

11+
const (
12+
ErrDuplicateEmail = "\"uni_users_email\" (SQLSTATE 23505)"
13+
ErrWrongPassword = "password"
14+
ErrNotFoundSQL = "sql: no rows in result set"
15+
)
16+
1017
type CustomHttpError struct {
1118
Code int
1219
Message string
1320
OriginError error
1421
}
1522

1623
func (e *CustomHttpError) Error() string {
24+
if e.OriginError != nil {
25+
return fmt.Sprintf("%s: %s", e.Message, e.OriginError.Error())
26+
}
1727
return e.Message
1828
}
1929

@@ -41,8 +51,8 @@ func NewInternalServerError(err error) *CustomHttpError {
4151
}
4252
}
4353

44-
func CheckError(err, sub, message string, code int) (domain.HttpResponse, bool) {
45-
if strings.Contains(err, sub) {
54+
func CheckError(errStr, containsStr, message string, code int) (domain.HttpResponse, bool) {
55+
if strings.Contains(errStr, containsStr) {
4656
return domain.HttpResponse{
4757
Code: code,
4858
Message: message,
@@ -52,19 +62,23 @@ func CheckError(err, sub, message string, code int) (domain.HttpResponse, bool)
5262
}
5363

5464
func CustomErrorResponse(err error) domain.HttpResponse {
65+
fmt.Println("YOW", err)
5566
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)
67+
var errStr string
68+
if customErr.OriginError != nil {
69+
errStr = customErr.OriginError.Error()
70+
}
71+
resp, ok := CheckError(errStr, ErrDuplicateEmail, "User already exist", 400)
5872
if ok {
5973
return resp
6074
}
6175

62-
resp, ok = CheckError(errStr, "\"uni_logout_token\" (SQLSTATE 23505)", "You have already logged out.", 400)
76+
resp, ok = CheckError(errStr, ErrWrongPassword, "Sorry, your password is incorrect", 400)
6377
if ok {
6478
return resp
6579
}
6680

67-
resp, ok = CheckError(errStr, "password", "Sorry, your password is incorrect", 400)
81+
resp, ok = CheckError(errStr, ErrNotFoundSQL, "Data not found", http.StatusNotFound)
6882
if ok {
6983
return resp
7084
}

0 commit comments

Comments
 (0)