🐛 Fix error handling and logging

This commit is contained in:
2024-03-13 17:26:30 +04:00
parent 6265458bc3
commit 5af2714abb
8 changed files with 92 additions and 25 deletions

View File

@ -1,10 +1,10 @@
package db
import (
"errors"
"log"
"sync"
"github.com/aykhans/oh-my-url/app/errors"
"github.com/aykhans/oh-my-url/app/utils"
"github.com/gocql/gocql"
)
@ -58,11 +58,11 @@ func (c *Cassandra) CreateURL(url string) (string, error) {
applied, err := c.db.Query(query, id, key, url, 0).Consistency(gocql.All).MapScanCAS(m)
if err != nil {
log.Println(err)
return "", err
return "", errors.ErrDBCreateURL
}
if !applied {
log.Println("Failed to insert unique key")
return "", errors.New("an error occurred, please try again later")
return "", errors.ErrDBCreateURL
}
c.currentID.ID = id
@ -76,7 +76,11 @@ func (c *Cassandra) GetURL(key string) (string, error) {
Consistency(gocql.One).
Scan(&url)
if err != nil {
return "", err
log.Println(err)
if err == gocql.ErrNotFound {
return "", errors.ErrDBURLNotFound
}
return "", errors.ErrDBGetURL
}
return url, nil
}

View File

@ -1,6 +1,9 @@
package db
import (
"log"
"github.com/aykhans/oh-my-url/app/errors"
"gorm.io/gorm"
)
@ -9,10 +12,10 @@ type Postgres struct {
}
type url struct {
ID uint `gorm:"primaryKey"`
Key string `gorm:"unique;not null;size:15;default:null"`
URL string `gorm:"not null;default:null"`
Count int `gorm:"not null;default:0"`
ID uint `gorm:"primaryKey"`
Key string `gorm:"unique;not null;size:15;default:null"`
URL string `gorm:"not null;default:null"`
Count int `gorm:"not null;default:0"`
}
func (p *Postgres) Init() {
@ -30,7 +33,8 @@ func (p *Postgres) CreateURL(mainUrl string) (string, error) {
url := url{URL: mainUrl}
tx := p.gormDB.Create(&url)
if tx.Error != nil {
return "", tx.Error
log.Println(tx.Error)
return "", errors.ErrDBCreateURL
}
return url.Key, nil
}
@ -39,7 +43,11 @@ func (p *Postgres) GetURL(key string) (string, error) {
var result url
tx := p.gormDB.Where("key = ?", key).First(&result)
if tx.Error != nil {
return "", tx.Error
log.Println(tx.Error)
if tx.Error == gorm.ErrRecordNotFound {
return "", errors.ErrDBURLNotFound
}
return "", errors.ErrDBGetURL
}
result.Count++
p.gormDB.Save(&result)