第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 api 響應(yīng)中返回 postgres 錯誤

在 api 響應(yīng)中返回 postgres 錯誤

Go
蕪湖不蕪 2022-08-01 10:20:30
我的代碼中有兩個簡單的api方法。具有 endpoind 的方法創(chuàng)建用戶。領(lǐng)域是獨(dú)一無二的。當(dāng)我嘗試使用數(shù)據(jù)庫中已經(jīng)存在的相同用戶名創(chuàng)建用戶時,我在控制臺中出現(xiàn)錯誤:/api/user/createusername(/home/andrej/go/src/go_contacts/models/users.go:19) [2020-12-23 22:03:10]  pq: duplicate key value violates unique constraint "users_username_key"我想顯示此錯誤以響應(yīng)用戶,或者以某種方式識別代碼中的錯誤類型,以便為用戶顯示不同的錯誤消息。我只知道,如果我有錯誤,返回我id = 0。但對于用戶來說,這似乎不是一個好消息。usermain.gopackage mainimport (    "fmt"    "go_contacts/controllers"    "net/http"    "os"    "github.com/gorilla/mux"    "github.com/joho/godotenv")func main() {    godotenv.Load(".env")    router := mux.NewRouter()    router.HandleFunc("/", controllers.ReturnHello).Methods("GET")    router.HandleFunc("/api/user/create", controllers.CreateUser).Methods("POST")    port := os.Getenv("PORT")    if port == "" {        port = "8000"    }    err := http.ListenAndServe(":"+port, router)    if err != nil {        fmt.Print(err)    }}models.go使用用戶結(jié)構(gòu):package modelsimport (    u "go_contacts/utils"    "github.com/jinzhu/gorm")// User base modeltype User struct {    gorm.Model    Username string `json:"username" gorm:"unique"`    Password string `json:"password"`    Email    string `json:"email"`}// Create new userfunc (user *User) Create() map[string]interface{} {    GetDB().Create(user)    if user.ID <= 0 {        return u.Message(false, "Failed to create user, connection error.")    }    response := u.Message(true, "Account has been created")    response["user"] = user    return response}
查看完整描述

2 回答

?
吃雞游戲

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超7個贊

至于 pq v1.5.2 和 gorm v1.9.12


首先,您需要確定創(chuàng)建方法調(diào)用是否返回錯誤。這樣


err := GetDB().Create(user).Error

if err != nil {

    // code to handle error

}

然后pq包具有映射到postgres服務(wù)器錯誤的特殊類型。它包含可以幫助您識別錯誤嚴(yán)重性,代碼,與錯誤相關(guān)的表等字段。


psql 字段標(biāo)識符的完整列表可以在


錯誤和通知消息字段


https://www.postgresql.org/docs/current/protocol-error-fields.html


要解決您的問題作為一個選項(xiàng),我們可以使用字段


Code

這是錯誤代碼的字符串類型表示形式。但首先,我們需要強(qiáng)制轉(zhuǎn)換錯誤并檢查類型轉(zhuǎn)換是否成功。這樣


err := GetDB().Create(user).Error

if err != nil {

    pqErr, ok := err.(pq.Error)

    if !ok {

        log.Fatal(err)

    }


    // code to handle specific error code

}

錯誤代碼列表可以在官方postgresql文檔中找到 https://www.postgresql.org/docs/9.3/errcodes-appendix.html


以及實(shí)際轉(zhuǎn)到pq庫中 github.com/lib/pq/error.go 的錯誤進(jìn)行pq特定映射


最后,我們可以通過代碼將錯誤處理為重復(fù)錯誤


err := GetDB().Create(user).Error

if err != nil {

    pqErr, ok := err.(pq.Error)

    if !ok {

        log.Fatal(err)

    }


    // note that type casting here is redundant and used for showing specific 

    // string type from pq library

    if pqErr.Code == pq.ErrorCode("23505") { // 23505 is unique_violation error code for psql

        // now you can create error and write it to a message to return it for 

        // a client

    }

}


查看完整回答
反對 回復(fù) 2022-08-01
?
蝴蝶不菲

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超4個贊

根據(jù)注釋,gorm 提供對“創(chuàng)建記錄”函數(shù)中數(shù)據(jù)庫錯誤的訪問,如下所示:


result := GetDB().Create(user)

if result.Error != nil {

   // Do something with the error

}

請注意,檢查錯誤字符串可能會使您的應(yīng)用程序數(shù)據(jù)庫成為特定數(shù)據(jù)庫(但這可能不是您的問題)。這個問題的答案可能會提供進(jìn)一步的幫助。



查看完整回答
反對 回復(fù) 2022-08-01
  • 2 回答
  • 0 關(guān)注
  • 89 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號