Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the error returned by db.Exec(...) have a code?

I'm trying to delete a database using the postgres driver (lib/pq) by doing a:

db.Exec("DROP DATABASE dbName;")

But I'd like to do a different conditional based on whether the error received is something strange, or is a "database does not exist" error.

Is there a constant variable or something I can use to check if the error returned is a "database does not exist" error message, or would I have to manually parse the error string myself?

I tried to look in the documentation, but could not find anything for "database does not exist". I did however find this list.

Perhaps it fits under some other error code? Also I'm not quite sure the semantically correct way of fetching and comparing the error codes through the Postgres driver. I presume I should do something like this:

if err.ErrorCode != "xxx"
like image 333
b0xxed1n Avatar asked Jun 01 '16 05:06

b0xxed1n


2 Answers

The lib/pq package may return errors of type *pq.Error, which is a struct. If it does, you may use all its fields to inspect for details of the error.

This is how it can be done:

if err, ok := err.(*pq.Error); ok {
    // Here err is of type *pq.Error, you may inspect all its fields, e.g.:
    fmt.Println("pq error:", err.Code.Name())
}

pq.Error has the following fields:

type Error struct {
    Severity         string
    Code             ErrorCode
    Message          string
    Detail           string
    Hint             string
    Position         string
    InternalPosition string
    InternalQuery    string
    Where            string
    Schema           string
    Table            string
    Column           string
    DataTypeName     string
    Constraint       string
    File             string
    Line             string
    Routine          string
}

The meaning and possible values of these fields are Postres specific and the full list can be found here: Error and Notice Message Fields

like image 124
icza Avatar answered Nov 18 '22 11:11

icza


You could use this: https://github.com/omeid/pgerror

It has lots of mappings for various postgres errors.

With the package, you can do the following (taken from the README):

// example use:
_, err = stmt.Exec(SomeInsertStateMent, params...)
if err != nil {
  if e := pgerror.UniqueViolation(err); e != nil {
  // you can use e here to check the fields et al
    return SomeThingAlreadyExists
  }

  return err // other cases.
}
like image 1
ekundayo Avatar answered Nov 18 '22 12:11

ekundayo