Refactor event error handling.

This commit is contained in:
poljar (Damir Jelić) 2018-02-14 11:11:54 +01:00
parent 773085b515
commit 1029ce5c1b

View file

@ -47,6 +47,24 @@ class MatrixErrorEvent(MatrixEvent):
if self.fatal: if self.fatal:
self.server.disconnect(reconnect=False) self.server.disconnect(reconnect=False)
@classmethod
def from_dict(cls, server, error_prefix, fatal, parsed_dict):
try:
message = "{prefix}: {error}.".format(
prefix=error_prefix,
error=parsed_dict["error"])
return cls(
server,
message,
fatal=fatal
)
except KeyError:
return cls(
server,
("{prefix}: Invalid JSON response "
"from server.").format(prefix=error_prefix),
fatal=fatal)
class MatrixLoginEvent(MatrixEvent): class MatrixLoginEvent(MatrixEvent):
def __init__(self, server, user_id, access_token): def __init__(self, server, user_id, access_token):
@ -70,18 +88,12 @@ class MatrixLoginEvent(MatrixEvent):
parsed_dict["access_token"] parsed_dict["access_token"]
) )
except KeyError: except KeyError:
try: return MatrixErrorEvent.from_dict(
message = "Error logging in: {}.".format(parsed_dict["error"])
return MatrixErrorEvent(
server, server,
message, "Error logging in",
fatal=True True,
parsed_dict
) )
except KeyError:
return MatrixErrorEvent(
server,
"Error logging in: Invalid JSON response from server.",
fatal=True)
class MatrixSendEvent(MatrixEvent): class MatrixSendEvent(MatrixEvent):
@ -125,16 +137,9 @@ class MatrixSendEvent(MatrixEvent):
message message
) )
except KeyError: except KeyError:
try: return MatrixErrorEvent.from_dict(
message = "Error sending message: {}.".format(parsed_dict["error"])
return MatrixErrorEvent(
server, server,
message, "Error sending message",
fatal=False True,
parsed_dict
) )
except KeyError:
return MatrixErrorEvent(
server,
("Error sending message: Invalid JSON response "
"from server."),
fatal=False)