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.
This commit is contained in:
miruka 2020-10-18 14:28:41 -04:00
parent 52b0bb18cb
commit ac111603da

View File

@ -21,17 +21,19 @@ class MatrixError(Exception):
def from_nio(cls, response: nio.ErrorResponse) -> "MatrixError": def from_nio(cls, response: nio.ErrorResponse) -> "MatrixError":
"""Return a `MatrixError` subclass from a nio `ErrorResponse`.""" """Return a `MatrixError` subclass from a nio `ErrorResponse`."""
# Check for the M_CODE first: some errors for an API share the same http_code = response.transport_response.status
# http code, but have different M_CODEs (e.g. POST /login 403). m_code = response.status_code
for subcls in cls.__subclasses__():
if subcls.m_code and subcls.m_code == response.status_code:
return subcls()
for subcls in cls.__subclasses__(): 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 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 @dataclass
@ -91,7 +93,7 @@ class MatrixTooLarge(MatrixError):
@dataclass @dataclass
class MatrixBadGateway(MatrixError): class MatrixBadGateway(MatrixError):
http_code: int = 502 http_code: int = 502
m_code: str = "" m_code: Optional[str] = None
# Client errors # Client errors