database-js icon indicating copy to clipboard operation
database-js copied to clipboard

Descriptive body for errors

Open twiddler opened this issue 1 year ago • 1 comments

I am trying to catch exceptions when inserting duplicates that violate a UNIQUE constraint. Node prints the exception as

… caused DatabaseError: target: ….-.primary: vttablet: rpc error: code = AlreadyExists desc = Duplicate entry 'foo' for key 'SomeTable.someAttribute' (errno 1062) (sqlstate 23000) (CallerID: …): Sql: "insert into SomeTable(someAttribute) values (:vtg1 /* VARCHAR */)", BindVars: {REDACTED}

console.log(e) gives me

{
  status: 400,
  body: {
    message: 'target: ….-.primary: vttablet: rpc error: code = AlreadyExists desc = Duplicate entry \'foo\' for key \'SomeTable.someAttribute\' (errno 1062) (sqlstate 23000) (CallerID: …): Sql: "insert into SomeTable(`someAttribute`) values (:vtg1 /* VARCHAR */)", BindVars: {REDACTED}',
    code: 'UNKNOWN'
  }
}

I can parse that message with a regex to extract the code and everything, but I think it'd make more sense to have a few more fields that digest that information already (errno would probably be the most helpful, at least for my use case).

One could also take that a step further and introduce more classes that derive https://github.com/planetscale/database-js/blob/f62005c7e5d31a1e1b475ee6aad7f20ca3dba911/src/index.ts#L15 but I suspect that might get out of hand quickly. I just checked out the MySQL error reference and it's enormous.

Also code: 'UNKNOWN' seems a bit odd, unless it does not describe any of code, errno or sqlstate.

twiddler avatar Nov 18 '24 21:11 twiddler