I am writing an API function using DRF where I want the API execution to stop if it fails in any of the steps and return an appropriate response. So I created a custom exception which takes an error code, and an error message like below.
class CustomException(Exception):
def __init__(self, status, msg):
self.status = status
self.message = msg
super().__init__(self.message + ': ' + str(self.status))
And I came up with the below code structure for the API function,
def place_order(request):
err_msg = 'Problem in placing order. Please contact us'
try:
response = is_cart_empty()
if response.status == 0:
err_msg = 'Cart cannot be empty'
raise CustomException(0, err_msg)
# Do something...
response = is_valid_user()
if response.status == 0:
err_msg = 'User is not valid'
raise CustomException(0, err_msg)
# Do something...
response = is_product_available()
if response.status == 0:
err_msg = 'Product out of stock'
raise CustomException(0, err_msg)
# Do something...
response_data = {
'status': 1,
'order_id': '1235'
}
except CustomException as e:
response_data = {
'status': e.status,
'error_message': e.message
}
except Exception as e:
traceback.print_exc()
print(e)
response_data = {
'status': 0,
'error_message': err_msg
}
return Response(data=json.dumps(response_data), status=status.HTTP_200_OK)
Is this is a good design approach ? Is there any better/alternative way we can handle this ?
Is this is a good design approach-- Does it effectively meet your specific software requirements?