i am currently working on my api and wanted to implement a mechanism that i can raise a custom exception at any point and return a json response:
class InvalidUsage(Exception):
def __init__(self, message):
Exception.__init__(self)
self.message = message
def to_json(self):
return JsonResponse(False, self.message)()
class JsonResponse(object):
def __init__(self, success, data):
self.success = success
self.data = data
if not success:
self.result = {
'success': self.success,
'error': self.data
}
else:
self.result = {
'success': self.success,
'data': self.data
}
def __call__(self):
return jsonify({'result': self.result})
When i try to use it in any controller:
raise InvalidUsage('Some error ocurred').to_json()
it just prints a Traceback back to:
raise InvalidUsage('Some error ocurred').to_json()
But JsonResponse works perfectly fine. When i run:
return JsonResponse(False, 'Some error ocurred')()
it returns correct json to my browser.
But i need to get my exception raise somehow working.. so i can raise api exceptions at any point in my python-webapp(controller, service, validator, etc..)
Anybody could help me to figure out how to do this?
Thanks and Greetings!
raiseinstructionraiseinstruction could possibly work sinceraiseaccepts an object inheriting from BaseException and your are giving it a flaskResponseviajsonify