簡體   English   中英

我如何訪問golang中的錯誤個別屬性

[英]How can i access error individual attributes in golang

!! 我是 go 的新手!!

我正在使用數據同步 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_)

我go哪里錯了?

Go 的 AWS SDK 中的錯誤通常是接口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)

代碼的 rest 基本上只是檢查,如果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())
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM