python - Passing an object with an Exception? -
what correct way pass object custom exception? i'm pretty sure code used work, throwing error.
class failedpostexception(exception): pass def post_request(request): session = requests.session() response = session.send(request.prepare(), timeout=5, verify=true) if response.status_code not requests.codes.ok: raise failedpostexception(response) session.close() return response try: ... except failedpostexception r: // type(r) - requests.response print r.text attributeerror: 'failedpostexception' object has no attribute 'text'
the raising , catching of exception correct, issue here expect exception have text attribute not exist. when inheriting built-in exception type can use args attribute, tuple of arguments exception, example:
try: ... except failedpostexception r: print r.args[0] in case use str(r) instead of r.args[0]. if there 1 argument exception str(r) equivalent str(r.args[0]), otherwise equivalent str(r.args).
if want add text attribute failedpostexception, can following:
class failedpostexception(exception): def __init__(self, text, *args): super(failedpostexception, self).__init__(text, *args) self.text = text note in python 3.x can use super().__init__(text, *args).
Comments
Post a Comment