dongyoufo5672 2018-12-06 22:18
浏览 37
已采纳

如何通过Struct字段名称获取Gmail API错误代码?

The Gmail API err response struct includes a Code field according to Examiner

_, err := gmailService.Users.Messages.Send("me", &gMsg).Do()
t := reflect.TypeOf(err)
examiner(t,0)

Response

Type is  and kind is ptr
 Contained type:
 Type is Error and kind is struct
     Field 1 name is Code type is int and kind is int
...

I can successfully get the error code using the field index, but that is more obscure (and therefore more difficult to maintain) and feels more fragile:

errReflectElem := reflect.ValueOf(err).Elem() 
fmt.Printf("err.Code %v
",errReflectElem.Field(0).Interface())

It appears that I should also be able to get the error code as follows based on this sample:

fmt.Println("Code: %v",err.Code)

However that gives a build error:

err.Code undefined (type error has no field or method Code)

What am I missing?

  • 写回答

1条回答 默认 最新

  • doudu2591 2018-12-06 22:41
    关注

    According to the documentation it returns a *googleapi.Error. Simply assert to this type and you have full access to everything it contains. This is a prime example of the power of interfaces and proper error handling via an exported type. If such an error type is exported, there is no reflection necessary to access it.

    if gapiErr, ok := err.(*googleapi.Error); ok {
        // use gapiErr.WhateverField
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 WPF动态创建页面内容
  • ¥15 如何对TBSS的结果进行统计学的分析已完成置换检验,如何在最终的TBSS输出结果提取除具体值及如何做进一步相关性分析
  • ¥15 SQL数据库操作问题
  • ¥100 关于lm339比较电路出现的问题
  • ¥15 Matlab安装yalmip和cplex功能安装失败
  • ¥15 加装宝马安卓中控改变开机画面
  • ¥15 STK安装问题问问大家,这种情况应该怎么办
  • ¥15 关于罗技鼠标宏lua文件的问题
  • ¥15 halcon ocr mlp 识别问题
  • ¥15 已知曲线满足正余弦函数,根据其峰值,还原出整条曲线