I’m writing an Azure Functions API, with many different endpoints with similar internal behavior. One major step in each endpoint is to take each naked POST and parse out any and all arguments (comes in as a dictionary) to a custom request object I define that can be further used for all function behavior. Each request object expects certain keys to be present in the request’s data, and I raise exceptions within the object to direct program flow within the main function towards an early response with error code.
My main question is: I have to reuse these try...except
blocks in every function as I want the responses to be the same, is there a way to abstract this out to a single reusable block?
This is an example of how one endpoint would look:
from requests import ShowUsersRequest
def my_function(req: azure.functions.HttpRequest):
try:
wrapped_request = ShowUsersRequest(req)
except KeyError:
return func.HttpResponse('Request missing argument(s)', status_code=400)
except ValueError as e:
return func.HttpResponse(f'One or more request arguments was of invalid type. {e.args[0]}', status_code=400)
... # rest of function continues
And what a request object would look like:
# requests.py
class ShowUsersRequest:
def __init__(self, req: func.HttpRequest) -> None:
# KeyErrors would arise from a missing key in the params dict
self.identifier = req.params['account_identifier']
self.client_code = int(req.params['client_code'])
# raise ValueError to represent some kind of validation problem
if self.client_code < 0:
raise ValueError('Client code must be non-negative')