项目作者: Shyp

项目描述 :
parsing postgres errors
高级语言: Go
项目地址: git://github.com/Shyp/go-dberror.git
创建时间: 2016-02-08T06:16:34Z
项目社区:https://github.com/Shyp/go-dberror

开源协议:

下载


Readable database errors

Do you like forcing constraint validation down into the database, but dislike
the native error messages returned by Postgres?

invalid input syntax for uuid: “foo”

invalid input value for enum account_status: “blah”

new row for relation “accounts” violates check constraint “accounts_balance_check”

null value in column \”id\” violates not-null constraint

This library attempts to parse those error messages and return error messages
that you can expose via your API.

No id was provided. Please provide a id

Cannot write a negative balance

Invalid input syntax for type uuid: “foo”

Invalid account_status: “blah”

Can’t save to payments because the account_id (91f47e99-d616-4d8c-9c02-cbd13bceac60) isn’t present in the accounts table

A email already exists with this value (test@example.com)

In addition, this library exports common Postgres error codes, so you can check
against them in your application.

Basic Usage

  1. import dberror "github.com/Shyp/go-dberror"
  2. func main() {
  3. _, err := db.Exec("INSERT INTO accounts (id) VALUES (null)")
  4. dberr := dberror.GetError(err)
  5. switch e := dberr.(type) {
  6. case *dberror.Error:
  7. fmt.Println(e.Error()) // "No id was provided. Please provide a id"
  8. default:
  9. // not a pq error
  10. }

Database Constraints

Failed check constraints are tricky - the native error messages just say
“failed”, and don’t reference a column.

So you can define your own constraint handlers, and then register them:

  1. import dberror "github.com/Shyp/go-dberror"
  2. import "github.com/lib/pq"
  3. func init()
  4. constraint := &dberror.Constraint{
  5. Name: "accounts_balance_check",
  6. GetError: func(e *pq.Error) *dberror.Error {
  7. return &dberror.Error{
  8. Message: "Cannot write a negative balance",
  9. Severity: e.Severity,
  10. Table: e.Table,
  11. Detail: e.Detail,
  12. Code: string(e.Code),
  13. }
  14. },
  15. }
  16. dberror.RegisterConstraint(constraint)
  17. // test.AssertEquals(t, e.Error(), "Cannot write a negative balance")
  18. }

If we get a constraint failure, we’ll call your GetError handler, to get
a well-formatted message.