2
votes

I am trying to get values from dynamodb using partition key, the code is working fine if partition key value is found. But when partition key is not found exception is thrown and its not getting catched.

In the code i have made use of custom layer d_c_fun which has logger function defined in that. I have tried elseif function with below logic. if partition key "data_id" is found then values is returned properly. but when key value is not present it is throwing error instead of giving response as from exception blocks as below.

import json
import boto3
import logging
import d_c_fun as cf

LOGGER = cf.get_logger()
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('tablename')
def lambda_handler(event, context):

    LOGGER.lambda_init(event, context)
    # Event value received through trigger

    D_Id = event['D_Id']
    if not D_Id:
        raise Exception ("data_id value not passed")
        #LOGGER.error(""data_id value not passed"")
    elif D_Id :
        resp = table.get_item(Key={
        "data_id":D_Id})
        LOGGER.info("Response Output value for the %s: %s", D_Id, resp['Item'])
        return resp['Item']
    else:
        raise Exception ("The data_id - %s provided doesn't exist in db", D_Id)

1) o/p: When data_id is matched in table as below.

Input event

{ "D_Id": "data2" }

output from code:

{ "table_name": "data2", "data_id": "data2" }

2) o/p: When data_id is not matched table as below.

input event value:

{ "D_Id": "data" }

output from code:

{ "errorMessage": "'Item'", "errorType": "KeyError",
"stackTrace": [ " File \"/var/task/demo.py\", line 23, in lambda_handler\n LOGGER.info(\"Response Output value for the %s: %s\", D_Id, resp['Item'])\n" ] }

Expected o/p should be in case of data_id is not matched.

The data_id - data provided doesn't exist in db".

3) o/p: When data_id is pass as null value.

input event value:

{ "D_Id": "" }

output from code:

{ "errorMessage": "data_id value not passed", "errorType": "Exception", "stackTrace": [ " File \"/var/task/demo.py\", line 18, in lambda_handler\n raise Exception (\"data_id not set\")\n" ] }

expected output should be.

"errorMessage": "data_id value not passed",

2

2 Answers

1
votes

I have developed this code as well and its working as expected :).

    import json
    import boto3
    import logging
    from botocore.exceptions import ClientError

    import d_c_fun as cf

    LOGGER = cf.get_logger()
    def get_dynamodb_client():
    dynamodb = boto3.client('dynamodb', region_name='REGION_NAME')
    return dynamodb


    def get_dynamodb_resource():
    dynamodb = boto3.resource('dynamodb', region_name='REGION_NAME')
    return dynamodb   


    def lambda_handler(event, context):
    D_Id = event['D_Id']

    if not D_Id:
        raise NameError("Field data_id is empty, Please enter data_id")
        return resp['Item']

    resp = get_dynamodb_resource().Table("TABLE_NAME").get_item(Key={
            "data_id":D_Id})

    if 'Item' not in resp:
        raise KeyError(
                'Data "{}" not found. '.format(D_Id) +
                'Please enter valid data_id.'
            )
        return resp['Item']
   else:
       LOGGER.info("Got the Item Successfully - \n %s", resp['Item'])
       return resp['Item']
0
votes

My original answer is totally out of your purpose. Try this.

import json
import boto3
import logging
import d_c_fun as cf

LOGGER = cf.get_logger()
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('tablename')
def lambda_handler(event, context):

    LOGGER.lambda_init(event, context)
    # Event value received through trigger

    D_Id = event['D_Id']
    if not D_Id:
        raise Exception ("data_id value not passed")
        #LOGGER.error(""data_id value not passed"")
    else:
        try:
            resp = table.get_item(Key={"data_id":D_Id})
            LOGGER.info("Response Output value for the %s: %s", D_Id, resp['Item'])
            return resp['Item']
        except:
            raise Exception ("The data_id - %s provided doesn't exist in db", D_Id)