为了账号安全,请及时绑定邮箱和手机立即绑定

我如何访问golang中的错误个别属性

我如何访问golang中的错误个别属性

Go
翻阅古今 2022-11-23 16:06:22

我正在使用数据同步 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_ undefined (type error has no field or method Message_)


我哪里做错了 ?


查看完整描述

1 回答

?
潇湘沐

TA贡献1526条经验 获得超6个赞

AWS SDK for Go 中的错误通常是接口错误awserr.Error(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)

cast 的返回值是特定的错误awsErr和一个bool指示 cast 是否有效的值 ( 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())

}


查看完整回答
反对 回复 5天前

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信