From ac111603daa05bf45423cb4103d0b65e2ac6bf13 Mon Sep 17 00:00:00 2001 From: miruka Date: Sun, 18 Oct 2020 14:28:41 -0400 Subject: [PATCH] Fix err with no M_CODE falling back on wrong class When we received server errors with no matrix M_CODE, the MatrixError class would fall back to its first subclass that had a matching HTTP status code. This notably caused any 401 error to be interpreted as MatrixInvalidAccessToken, and disconnect the user. --- src/backend/errors.py | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/src/backend/errors.py b/src/backend/errors.py index d2df6bce..1e75b66e 100644 --- a/src/backend/errors.py +++ b/src/backend/errors.py @@ -21,17 +21,19 @@ class MatrixError(Exception): def from_nio(cls, response: nio.ErrorResponse) -> "MatrixError": """Return a `MatrixError` subclass from a nio `ErrorResponse`.""" - # Check for the M_CODE first: some errors for an API share the same - # http code, but have different M_CODEs (e.g. POST /login 403). - for subcls in cls.__subclasses__(): - if subcls.m_code and subcls.m_code == response.status_code: - return subcls() + http_code = response.transport_response.status + m_code = response.status_code for subcls in cls.__subclasses__(): - if subcls.http_code == response.transport_response.status: + if subcls.m_code and subcls.m_code == m_code: return subcls() - return cls(response.transport_response.status, response.status_code) + # If error doesn't have a M_CODE, look for a generic http error class + for subcls in cls.__subclasses__(): + if not subcls.m_code and subcls.http_code == http_code: + return subcls() + + return cls(http_code, m_code) @dataclass @@ -90,8 +92,8 @@ class MatrixTooLarge(MatrixError): @dataclass class MatrixBadGateway(MatrixError): - http_code: int = 502 - m_code: str = "" + http_code: int = 502 + m_code: Optional[str] = None # Client errors