Aws-sdk-go: What's the proper way to check if GetItem didn't found record?

Created on 20 Jan 2016  路  4Comments  路  Source: aws/aws-sdk-go

What's the proper way to check if GetItem found item? Checking for resp.Item length?

    if len(resp.Item) == 0 {
        return nil, fmt.Errorf("Item not found")
    }

Full example

    params := &dynamodb.GetItemInput{
        Key: map[string]*dynamodb.AttributeValue{
            "token": {
                S: aws.String(token),
            },
        },
        ProjectionExpression: aws.String("json"),
        TableName:            aws.String("tokens"),
    }

    resp, err := self.db.GetItem(params)
    if err != nil {
        return nil, err
    }

    if len(resp.Item) == 0 {
        return nil, fmt.Errorf("Item not found")
    }
guidance

Most helpful comment

Correct, checking the length of resp.Item is the best way to know if a GetItem request returned a result. Are you seeing in issues where an empty map for Item causes conflicts?

All 4 comments

Correct, checking the length of resp.Item is the best way to know if a GetItem request returned a result. Are you seeing in issues where an empty map for Item causes conflicts?

The only issue I had was that I first didn't had the check if len(resp.Item) == 0 and so my code was panicking when I tried to get data with resp.Item["json"].
I think this a bit unusual approach, I would rather expect GetItem() returning a package defined error like ErrNotFound (example from sql world https://golang.org/pkg/database/sql/#pkg-variables). Harder to make mistake and end up with panic.

Thanks for answer!

Thanks for the feedback @arvenil I'll make sure to forward that along to the DynamoDB team. Glad to help. Let us know if you have any other questions, feedback, or ideas/features to improve the SDK.

Just ran into this.. strangest behaviour, would not have expected it. At the very least some extra documentation somewhere on the function would be useful, it seems ambiguous at best:

If there is no matching item, GetItem does not return any data
// and there will be no Item element in the response.

ErrCodeResourceNotFoundException "ResourceNotFoundException"
The operation tried to access a nonexistent table or index. The resource
might not be specified correctly, or its status might not be ACTIVE.

Thanks for this post existing though.

Was this page helpful?
0 / 5 - 0 ratings