OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Is there a clean way to handle reuse of try...except blocks that force early function return?

  • Thread starter Thread starter walkrflocka
  • Start date Start date
W

walkrflocka

Guest
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:

Code:
from requests import ShowUsersRequest

def my_endpoint(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:

Code:
# 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')
<p>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.</p>
<p>My main question is: I have to reuse these <code>try...except</code> 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?</p>
<p>This is an example of how one endpoint would look:</p>
<pre class="lang-py prettyprint-override"><code>from requests import ShowUsersRequest

def my_endpoint(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
</code></pre>
<p>And what a request object would look like:</p>
<pre class="lang-py prettyprint-override"><code># 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')
</code></pre>
 

Latest posts

Top