I have this code which creates a team using the github API and returns the team-id(success) or -1(failure).
My problem is with the error handling. When the request responses with an error status code I try to deal with a few different types of failure. It looks like a mess!
Is there any way to make it more readable/elegant?
I'd also like to know if I am catching all the reasonable exceptions that can be thrown by requests.
def create_team(org,team_name):
'''
Try to create a team and return its id
if already exisits return id
'''
try:
data = {
"name": team_name,
"permission": "push"
}
headers = {'Authorization': 'token '+OAUTH_TOKEN}
response = requests.post(GH_API_URL+'orgs/'+org['login']+'/teams',
headers=headers,
data = json.dumps(data))
response.raise_for_status() #throw exception if request does not retun 2xx
#http status is 2xx, team must have been created
json_response = json.loads(response.text)
return json_response['id'] #get id of new team from response
except requests.exceptions.HTTPError as e:
if response.status_code == 422: #Unprocessable Entity
json_response = json.loads(response.text)
if json_response['errors'][0]['code'] == 'already_exists': #Unprocessable because already exists
print(' not created, team already exists!!!')
#get the id of existing team
team_id = get_teamID_from_name(org, team_name)
return team_id
else: #Unprocessable for some other reason
print(' HTTP error: '+str(e))
else: #other HTTP error != 422
print(' HTTP error: '+str(e))
except requests.exceptions.RequestException as e:
print('Connection error: '+str(e))
return -1
In case you were wondering why I don't just check for the existence of the team BEFORE trying to create it. That's because the normal case for this function is that the teams do not already exist and the github API is quite slow. As it stands it takes several minutes to process a groups with 50 teams and 100 students. Checking for team existence would add a few more minutes to the runtime.
IssueLog) come from? \$\endgroup\$