Open arcivanov opened 1 month ago
Such a change sounds sensible to me atleast. Probably want errors etc. to behave similarly to .receive().
One of the issues with receive
though, is that receive
returns WSMessage
with WSMsgType.ERROR
which is an implementation detail and should not be exposed to public API IMO. I.e. the current receive
should be _receive
, and the public implementation of receive
should wrap the _receive
to unwrap the WSMessage(WSMsgType.ERROR, exc, None)
to an exception at the very least.
It is part of the public API though, and explicitly mentioned in the docs (e.g. https://docs.aiohttp.org/en/stable/client_quickstart.html#websockets).
Maybe it makes sense to change the behaviour, but such a change would have to go into v4...
It is part of the public API though, and explicitly mentioned in the docs (e.g. https://docs.aiohttp.org/en/stable/client_quickstart.html#websockets).
This is in re receive
only, right? There is no way for this type of error handling in receive_string/binary/json
.
Describe the solution you'd like
The current API provides for a very bizarre/absent error handling mechanism for web socket receive operations.
Specifically these are the current implementations for receiving
string
,bytes
andjson
:https://github.com/aio-libs/aiohttp/blob/9ed3841f5d920360da1937eb440ff9cb60e7c2c6/aiohttp/client_ws.py#L298-L320
As you can see any message that is not of the type
TEXT
orBINARY
will result in aTypeError
raised. However, if we inspect the underlyingreceive
, we'll see that whole bunch of error and state conditions will produce messages that are neitherTEXT
norBINARY
, includingWS_CLOSED_MESSAGE
,WSMsgType.CLOSED
andWSMsgType.ERROR
(this one is internal API implementation and should never be exposed to a user anyway) [emphasis added by****
]:So, what happens when you
receive_str
on a closed web socket? -TypeError
Server-initiated socket closing?TypeError
TCP connection reset and disconnected?TypeError
The
TypeError
is a builtin, its only payload is a string and information about the state or exception is entirely lost except as encoded within the error string. This is clearly not a desired API behavior.In my application internally I had to implement my own wrapper of the
receive
as follows to ensure that:1) If WSS is closed normally a
None
is returned to indicateEOF
. 2) If we receive an unsolicited server closure, aServerDisconnectedError
is raised. 3) If an exception occurs during areceive
, the exception is unwrapped from theWSMessage(WSMsgType.ERROR, exc, None)
and re-raised.The code is as follows and I believe the API should change along the similar lines:
Code of Conduct