登录
首页 >  Golang >  Go问答

如何获取Golang中错误的单个字段值

来源:stackoverflow

时间:2024-02-28 16:36:23 419浏览 收藏

Golang小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《如何获取Golang中错误的单个字段值》带大家来了解一下##content_title##,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!


问题内容

!!我是新来的!!

我正在使用 datasync api 来启动任务执行,没有任何问题。我正在努力处理返回的错误结构,我想访问各个元素,但我似乎无法做到这一点。

例如,在以下错误中,我希望能够访问message_的内容

2022/03/19 09:33:48 sync called : 
invalidrequestexception: unable to queue the task execution for task task-xxxxxxxxxxxx. the task already has another task execution exec-030b4a31dc2e33641 currently running or queued with identical include and exclude filter patterns. please provide unique include and exclude filter patterns for the new task execution and try again.
{
  respmetadata: {
    statuscode: 400,
    requestid: "xxxxxxxxxxxxxxxxxxxxx"
  },
  errorcode: "dedupefailed",
  message_: "unable to queue the task execution for task task-xxxxxxxxxx. the task already has another task execution exec-xxxxxxxxxx currently running or queued with identical include and exclude filter patterns. please provide unique include and exclude filter patterns for the new task execution and try again."
}

这是我的工作示例:

// Create datasync service client
    svc := datasync.New(sess)

    params := &datasync.StartTaskExecutionInput{
        TaskArn : aws.String("arn:aws:datasync:*******************************"),
    }

    // start task execution
    resp, err := svc.StartTaskExecution(params)

    //err = req.Send()

    if err == nil { // resp is now filled
        fmt.Println(resp)  // this outputs this { TaskExecutionArn: "arn:aws:datasync:xxxxxxxx:task/task-03ecb7728e984e36a/execution/exec-xxxxxxxxxx" }

    } else {
        fmt.Println(err)
        //fmt.Println(err.Message()) THIS DOES NOT WORK
        //fmt.Println(err.Message_)  THIS ALSO DOES NOT WORK
    }

如果我这样做 fmt.println(err.message())this fmt.println(err.message_) 我得到这个 error err.message undefined (type error has no field or method message) err.message_未定义(类型错误没有字段或方法message_)

我哪里出错了?


正确答案


适用于 go 的 aws 开发工具包中的错误通常与接口 awserr.error (Code on Github) 有关。

如果您只是想收到消息,可以这样做:

resp, err := svc.starttaskexecution(params)

if err != nil {
    if awserr, ok := err.(awserr.error); ok {
        fmt.println(awserr.message())
    } else {
        fmt.println(err.error())
    }
}

首先,检查是否确实存在错误:

if err != nil {...}

然后,我们尝试将错误转换为其特定的“类型”awserr.error

err.(awserr.error)

强制转换的返回值是特定错误 awserrbool 来指示强制转换是否有效 (ok)。

awserr, ok := err.(awserr.error)

其余代码基本上只是检查 ok == true 是否存在,如果是这种情况,您可以访问错误字段,例如 message

if awserr, ok := err.(awserr.error); ok {
    fmt.println(awserr.message())
}

否则,您只需打印标准 go 错误消息:

if awsErr, ok := err.(awserr.Error); ok {
    ...
} else {
    fmt.Println(err.Error())
}

今天关于《如何获取Golang中错误的单个字段值》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>