2016-08-25 2 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' еще не инициализируется. Вы можете добавить 'job_id = None' или другое значение по умолчанию перед блоком' try', чтобы убедиться, что он будет назначен перед ссылкой на него. – Jezor

+0

Прежде чем 'UnboundLocalError' будет поднят,' print (e) 'должен выводить« KeyError », который, как я полагаю, заставил элемент управления переключиться на блок« except », прежде чем« job_id »получит значение. – chepner

ответ

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)) 
Смежные вопросы