11package utils
22
33import (
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+
1017type CustomHttpError struct {
1118 Code int
1219 Message string
1320 OriginError error
1421}
1522
1623func (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
5464func 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