I am quite new to Go Lang development. Recently I am using Aerospike Go client to getObject
err = aer.AeroDB.getObject(nil, key, Record)
if err != nil {
fmt.Println(err)
}
now the above error exposes only one method Error()
which returns a string. I need to handle each type of errors differently. How do I do this, as there are no error codes returned. Do I do string matching to get the relevant type?
SOLUTION: Answer and comments below helped me to find an exact answer. I will share it here with the rest. Aerospike libraries export AerospikeError
struct. Now, error could be nil or AerospikeError
struct
. Following code did the work.
import (
"errors"
"fmt"
aerospike "github.com/aerospike/aerospike-client-go"
"github.com/aerospike/aerospike-client-go/types"
)
type ArDB struct {
Host string
Port int
AeroDB *aerospike.Client
}
ArErr, failed := aer.AeroDB.GetObject(nil, key, Record).(types.AerospikeError)
if failed {
if ArErr.ResultCode() == types.KEY_NOT_FOUND_ERROR {
//Key is not present, create new data
Record = NewAudienceRecord()
} else {
//Handle other errors!
}
}
If the function returns errors which are actually of different type, then you should use type switch:
switch err.(type) {
case Error1:
fmt.Println("Error1", err)
case Error2:
fmt.Println("Error2", err)
default:
fmt.Println(err)
}
But if the errors are of same type then you have to see does the package export some "common errors" as variables, so that you can check against those:
if err == aer.Error1 {
// do something specific to Error1
}