dqmnueuu459279 2016-07-19 08:30
浏览 83
已采纳

在Go Lang中处理Aerospike库错误

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!
    }
}
  • 写回答

2条回答 默认 最新

  • duanna1407 2016-07-19 08:34
    关注

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题