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 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100