Skip to content

Commit 83540c2

Browse files
committed
chore(errors): handle errors better
1 parent d26ebef commit 83540c2

File tree

8 files changed

+74
-17
lines changed

8 files changed

+74
-17
lines changed

db/base_db.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ func (b *BaseDB[T]) Add(obj *T) error {
2828
Error
2929

3030
if err != nil {
31-
return err
31+
return tryWrapMySqlError(err)
3232
}
3333

3434
return nil
@@ -46,7 +46,7 @@ func (b *BaseDB[T]) AddMany(objs []*T) error {
4646
Error
4747

4848
if err != nil {
49-
return err
49+
return tryWrapMySqlError(err)
5050
}
5151

5252
return nil

db/errors.go

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,12 @@
11
package db
22

3-
import "dankmuzikk/errors"
3+
import (
4+
"dankmuzikk/errors"
5+
6+
goerrors "errors"
7+
8+
"github.com/go-sql-driver/mysql"
9+
)
410

511
var DbErrNamespace = errors.DankMuzikkErrNamespace.NewSubNamespace("database error")
612

@@ -10,4 +16,17 @@ var (
1016
ErrEmptySlice = DbErrNamespace.NewType("slice is nil or empty")
1117
ErrInvalidWhereConditions = DbErrNamespace.NewType("invalid where conditions")
1218
ErrRecordNotFound = DbErrNamespace.NewType("no records were found")
19+
ErrRecordExists = goerrors.New("record exists in table")
1320
)
21+
22+
func tryWrapMySqlError(err error) error {
23+
if mysqlErr, ok := err.(*mysql.MySQLError); ok {
24+
switch mysqlErr.Number {
25+
case 1062:
26+
return ErrRecordExists
27+
default:
28+
return err
29+
}
30+
}
31+
return err
32+
}

handlers/apis/email_login.go

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,10 @@ import (
88
"dankmuzikk/log"
99
"dankmuzikk/services/login"
1010
"dankmuzikk/views/components/otp"
11+
"dankmuzikk/views/components/status"
1112
"encoding/json"
13+
"errors"
14+
"fmt"
1215
"net/http"
1316
"time"
1417
)
@@ -32,7 +35,10 @@ func (e *emailLoginApi) HandleEmailLogin(w http.ResponseWriter, r *http.Request)
3235
verificationToken, err := e.service.Login(reqBody)
3336
if err != nil {
3437
log.Errorf("[EMAIL LOGIN API]: Failed to login user: %+v, error: %s\n", reqBody, err.Error())
35-
w.WriteHeader(http.StatusBadRequest)
38+
// w.WriteHeader(http.StatusInternalServerError)
39+
status.
40+
GenericError(fmt.Sprintf("No account associated with the email \"%s\" was found", reqBody.Email)).
41+
Render(context.Background(), w)
3642
return
3743
}
3844

@@ -56,9 +62,20 @@ func (e *emailLoginApi) HandleEmailSignup(w http.ResponseWriter, r *http.Request
5662
}
5763

5864
verificationToken, err := e.service.Signup(reqBody)
65+
if errors.Is(err, login.ErrAccountExists) {
66+
log.Errorf("[EMAIL LOGIN API]: Failed to sign up a new user: %+v, error: %s\n", reqBody, err.Error())
67+
// w.WriteHeader(http.StatusConflict)
68+
status.
69+
GenericError(fmt.Sprintf("An account associated with the email \"%s\" already exists", reqBody.Email)).
70+
Render(context.Background(), w)
71+
return
72+
}
73+
if errors.Is(err, login.ErrAccountNotFound) || errors.Is(err, login.ErrProfileNotFound) {
74+
75+
}
5976
if err != nil {
6077
log.Errorf("[EMAIL LOGIN API]: Failed to sign up a new user: %+v, error: %s\n", reqBody, err.Error())
61-
w.WriteHeader(http.StatusBadRequest)
78+
w.WriteHeader(http.StatusInternalServerError)
6279
return
6380
}
6481

handlers/apis/google_login.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
package apis
22

33
import (
4+
"context"
45
"dankmuzikk/config"
56
"dankmuzikk/handlers"
67
"dankmuzikk/log"
78
"dankmuzikk/services/login"
9+
"dankmuzikk/views/components/status"
810
"net/http"
911
"time"
1012
)
@@ -38,7 +40,10 @@ func (g *googleLoginApi) HandleGoogleOAuthLoginCallback(w http.ResponseWriter, r
3840

3941
sessionToken, err := g.service.Login(state, code)
4042
if err != nil {
41-
w.WriteHeader(http.StatusUnauthorized)
43+
// w.WriteHeader(http.StatusUnauthorized)
44+
status.
45+
GenericError("Account doesn't exist").
46+
Render(context.Background(), w)
4247
log.Errorln("[GOOGLE LOGIN API]: ", err)
4348
return
4449
}

services/login/email.go

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@ import (
99
"errors"
1010
"fmt"
1111
"math/rand"
12-
"strings"
1312
"time"
1413

1514
"golang.org/x/crypto/bcrypt"
@@ -37,14 +36,14 @@ func NewEmailLoginService(
3736
}
3837

3938
func (e *EmailLoginService) Login(user entities.LoginRequest) (string, error) {
40-
account, err := e.accountRepo.GetByConds("email = ?", user.Email)
39+
account, err := e.accountRepo.GetByConds("email = ? AND is_o_auth = 0", user.Email)
4140
if err != nil {
42-
return "", err
41+
return "", errors.Join(ErrAccountNotFound, err)
4342
}
4443

4544
profile, err := e.profileRepo.GetByConds("account_id = ?", account[0].Id)
4645
if err != nil {
47-
return "", err
46+
return "", errors.Join(ErrProfileNotFound, err)
4847
}
4948
profile[0].Account = account[0]
5049
profile[0].AccountId = account[0].Id
@@ -66,11 +65,14 @@ func (e *EmailLoginService) Signup(user entities.SignupRequest) (string, error)
6665
Email: user.Email,
6766
},
6867
Name: user.Name,
69-
Username: user.Email[:strings.Index(user.Email, "@")],
68+
Username: user.Email,
7069
}
7170

72-
// creating a new account will create the account underneeth it.
71+
// creating a new account will create the account underneath it.
7372
err := e.profileRepo.Add(&profile)
73+
if errors.Is(err, db.ErrRecordExists) {
74+
return "", errors.Join(ErrAccountExists, err)
75+
}
7476
if err != nil {
7577
return "", err
7678
}

services/login/errors.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
package login
2+
3+
import "errors"
4+
5+
var (
6+
ErrAccountNotFound = errors.New("account was not found")
7+
ErrProfileNotFound = errors.New("profile was not found")
8+
ErrAccountExists = errors.New("an account with the associated email already exists")
9+
)

services/login/google.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ import (
1111
"errors"
1212

1313
"net/http"
14-
"strings"
1514
"time"
1615

1716
"github.com/google/uuid"
@@ -66,7 +65,7 @@ func (g *GoogleLoginService) Login(state, code string) (string, error) {
6665
return "", err
6766
}
6867

69-
account, err := g.accountRepo.GetByConds("email = ?", googleUser.Email)
68+
account, err := g.accountRepo.GetByConds("email = ? AND is_o_auth = 1", googleUser.Email)
7069
if errorx.IsOfType(err, db.ErrRecordNotFound) || len(account) == 0 {
7170
return g.Signup(googleUser)
7271
}
@@ -95,12 +94,13 @@ func (g *GoogleLoginService) Login(state, code string) (string, error) {
9594
func (g *GoogleLoginService) Signup(googleUser oauthUserInfo) (string, error) {
9695
profile := models.Profile{
9796
Account: models.Account{
98-
Email: googleUser.Email,
97+
Email: googleUser.Email,
98+
IsOAuth: true,
9999
},
100100
Name: googleUser.FullName,
101-
Username: googleUser.Email[:strings.Index(googleUser.Email, "@")],
101+
Username: googleUser.Email,
102102
}
103-
// creating a new account will create the account underneeth it.
103+
// creating a new account will create the account underneath it.
104104
err := g.profileRepo.Add(&profile)
105105
if err != nil {
106106
return "", err
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
package status
2+
3+
templ GenericError(msg string) {
4+
<h2 class={ "text-[#DE3333]", "text-xl", "font-semibold" }>{ msg }</h2>
5+
}

0 commit comments

Comments
 (0)