douyuepi6485
2015-04-29 18:24
浏览 41

如何在Go中解释PostgreSQL错误消息?

How can I parse SQL constraint errors, in particular resulting from constraints such as UNIQUE, FOREIGN KEY, NOT NULL, ON DELETE RESTRICT within Go?

e.g. Insert a new user that may have the same email which is defined as a UNIQUE field in the database. Parse constraint error in Go, return error to browser client.

图片转代码服务由CSDN问答提供 功能建议

如何解析SQL约束错误,尤其是由 UNIQUE 之类的约束引起的错误, Go中的 FOREIGN KEY NOT NULL ON DELETE RESTRICT

例如 插入一个新用户,该用户可能具有与数据库中定义为 UNIQUE 字段的电子邮件相同的电子邮件。 在Go中解析约束错误,将错误返回给浏览器客户端。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongmangsha7354 2015-04-29 22:17
    已采纳

    For information about how to interpret errors from github.com/lib/pq, see http://godoc.org/github.com/lib/pq#Error.

    Here is what I do:

    // ShowError sends an appropriate error message.
    func ShowError(w http.ResponseWriter, r *http.Request, err error) {
        switch e := err.(type) {
        case *pq.Error:
            switch e.Code {
            case "23502":
                // not-null constraint violation
                http.Error(w, fmt.Sprint("Some required data was left out:
    
    ", e.Message), http.StatusForbidden)
                return
    
            case "23503":
                // foreign key violation
                switch r.Method {
                case "DELETE":
                    http.Error(w, fmt.Sprint("This record can’t be deleted because another record refers to it:
    
    ", e.Detail), http.StatusForbidden)
                    return
                }
    
            case "23505":
                // unique constraint violation
                http.Error(w, fmt.Sprint("This record contains duplicated data that conflicts with what is already in the database:
    
    ", e.Detail), http.StatusForbidden)
                return
    
            case "23514":
                // check constraint violation
                http.Error(w, fmt.Sprint("This record contains inconsistent or out-of-range data:
    
    ", e.Message), http.StatusForbidden)
                return
    
            default:
                msg := e.Message
                if d := e.Detail; d != "" {
                    msg += "
    
    " + d
                }
                if h := e.Hint; h != "" {
                    msg += "
    
    " + h
                }
                http.Error(w, msg, http.StatusInternalServerError)
                return
            }
    
        case *strconv.NumError:
            http.Error(w, fmt.Sprintf(`"%s" is not a valid number.`, e.Num), http.StatusBadRequest)
            return
    
        default:
            switch err {
            case sql.ErrNoRows:
                http.NotFound(w, r)
                return
            }
        }
    
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题