2016-08-25 118 views
-1

这里的原因是我的代码:不明白例外

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 

请帮帮忙!

+0

所有你需要做的就是读取错误信息。在赋值之前引用的局部变量“job_id”意味着您正在尝试在初始化之前使用'job_id'。当你捕捉到一个异常时,'try'块中的变量还没有被初始化。您可以在'try'块之前添加'job_id = None'或其他一些默认值,以确保在引用它之前分配它。 – Jezor

+0

在引发'UnboundLocalError'之前,'print(e)'应该输出'KeyError',我认为在'job_id'被赋予一个值之前,我想让控制权切换到'except'块。 – chepner

回答

5

当您点击except块时,try块中的任何内容都不会保证运行。这包括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))