boltdb / bolt

An embedded key/value database for Go.
MIT License
14.24k stars 1.51k forks source link

How to check if a file is a valid boltdb database without panicing #733

Closed korjavin closed 7 years ago

korjavin commented 7 years ago
    d1 := []byte("hello\n")
    ioutil.WriteFile(filename, d1, 0644)

  dbconn, err := bolt.Open(filename, os.ModePerm, &bolt.Options{Timeout: 1 * time.Second})
    defer dbconn.Close()

This one will panic, but I would like to have just an err like "wrong format"

xyproto commented 7 years ago

You can recover from the panic with recover(), like this:

func canOpenDB(filename string) (retval bool) {
    defer func() {
        retval = nil == recover()
    }()
    dbconn, err := bolt.Open(filename, os.ModePerm, &bolt.Options{Timeout: 1 * time.Second})
    defer dbconn.Close()
        return nil == err
}
korjavin commented 7 years ago

It may work, thank you!