不要理解异常的原因

时间:2016-08-25 01:02:31

标签: python

这是我的代码:

import boto3
import json

client = boto3.client('elasticbeanstalk')
code_pipeline = boto3.client('codepipeline')

def put_job_success(job, message):
    print "Putting job success"
    print (message)
    code_pipeline.put_job_success_result(jobId=job)

def put_job_failure(job, message):
    print('Putting job failure')
    print(message)
    code_pipeline.put_job_failure_result(jobId=job, failureDetails={'message': message, 'type': 'JobFailed'})

def get_user_params(job_data):
    user_parameters = job_data['actionConfiguration']['configuration']['UserParameters']
    decoded_parameters = json.loads(user_parameters)
    print user_parameters

def lambda_handler(event, context):
    try:
        # Extract the Job ID
        job_id = event['CodePipeline.job']['id']

        # Extract the Job Data
        job_data = event['CodePipeline.job']['data']

        # Extract the params
        params = get_user_params(job_data)

        # Get the list of artifacts passed to the function
        artifacts = job_data['inputArtifacts']

        put_job_success(job_id, 'successfuly done')

    except Exception as e:

        # If any other exceptions which we didn't expect are raised
        # then fail the job and log the exception message.
        print('Function failed due to exception.')
        print(e)
        put_job_failure(job_id, 'Function exception: ' + str(e))

    print('Function complete.')
    return "Complete."

获取错误:

traceback (most recent call last):
  File "/var/task/lambda_function.py", line 48, in lambda_handler
    put_job_failure(job_id, 'Function exception: ' + str(e))
UnboundLocalError: local variable 'job_id' referenced before assignment

请帮忙!

1 个答案:

答案 0 :(得分:5)

一旦点击try块,except块中的任何内容都无法保证运行。这包括job_id作业。如果您想摆脱错误,可以尝试:

def lambda_handler(event, context):  
    job_id = None
    try:  
        # Extract the Job ID  
        job_id = event['CodePipeline.job']['id']  

        # Extract the Job Data    
        job_data = event['CodePipeline.job']['data']   

        # Extract the params  
        params = get_user_params(job_data)  

        # Get the list of artifacts passed to the function  
        artifacts = job_data['inputArtifacts']  

        put_job_success(job_id, 'successfuly done')  

    except Exception as e:  

        # If any other exceptions which we didn't expect are raised  
        # then fail the job and log the exception message.  
        print('Function failed due to exception.')   
        print(e)  
        put_job_failure(job_id, 'Function exception: ' + str(e))