Repository navigation
Description
Description
When constructing a WebSocketException, it is possible to specify a WebSocketError. One of these is WebSocketError.Faulted, "Indicates a general error."
However, that produces uninformative stacktraces (example below in "Actual behavior") that do not make the specific problem clear.
In this issue, I am suggesting 2 new WebSocketError values, WebSocketError.ProtocolError and WebSocketError.InvalidEncodedText (recommended uses described below).
This is technically a breaking change, since callers could be doing control flow based on WebSocketException.WebSocketErrorCode and expecting WebSocketError.Faulted specifically. However, I think that will be very rare in practice (especially because they would be expecting the most generic value), and the change will improve troubleshooting overall.
I didn't go through BrowserWebSocket (which does use WebSocketError.Faulted), ClientWebSocket (doesn't appear to use WebSocketError.Faulted), or other classes, so it may be worthwhile to expand this to include them.
Unlike the close codes, I do not believe these error codes are defined in the RFCs (see e.g. RFC 6455 sec. 8).
If WebSocketError.Faulted is used with no custom message, it maps to "An exception caused the WebSocket to enter the Aborted state. Please see the InnerException, if present, for more details." (Strings.resx).
This is vague. If there's no inner exception, the message is also a little circular (in that case, the exception causing it to Abort is this WebSocketException itself).
For case 2 below, the stacktrace does not provide any more insight into the specific error (in that case a text encoding error).
There are currently 5 uses of CloseWithReceiveErrorAndThrowAsync (private to ManagedWebSocket), which is one way the class throws WebSocketException:
ReceiveAsyncPrivate-TryParseMessageHeaderFromReceiveBufferfailure:
- Currently -
WebSocketError.Faulted, with specific message and no inner exception. - Could be new
WebSocketError.ProtocolError, which mirrorsWebSocketCloseStatus.ProtocolError. Can not beWebSocketError.HeaderError, since that is defined to refer to HTTP-level headers, not within-protocol WebSocket headers.
ReceiveAsyncPrivate- Payload not valid UTF-8:
- Currently
WebSocketError.Faulted, with no specific message or inner exception. - I recommend a new
WebSocketError.InvalidEncodedText.
HandleReceivedCloseAsync- Incorrect close payload length:
- Currently
WebSocketError.Faulted, with no specific error message or inner exception - I recommend a new
WebSocketError.ProtocolError(same as 1 above)
HandleReceivedCloseAsync- Invalid close status:
- Currently
WebSocketError.Faulted, with no specific error message or inner exception - I recommend a new
WebSocketError.ProtocolError(same as 1 above).
HandleReceivedCloseAsync- Failed to decode close status description as valid UTF-8:
- Currently
WebSocketError.Faulted, with an innerDecoderFallbackException, but no specific error message - I recommend a new
WebSocketError.InvalidEncodedText(same as 1 above).
I also grepped for new WebSocketException in ManagedWebSocket.cs. Other than CloseWithReceiveErrorAndThrowAsync, they are all WebSocketError.ConnectionClosedPrematurely. I don't see any necessary adjustments for these.
Reproduction Steps
For example 2 above ("Payload not valid UTF-8"), execute this to send non-UTF-8 bytes to a .NET 8 WebSocket server.
IMPORTANT: The exception in "Actual behavior" will be triggered on the receiving server, not on the client running the SendAsync. (EDITED)
await _webSocket.SendAsync(
buffer: new ArraySegment<byte>( Encoding.Unicode.GetBytes( "🙂" ) ),
messageType: WebSocketMessageType.Text,
endOfMessage: true,
cancellationToken: CancellationToken.None
);Expected behavior
For example 2 above ("Payload not valid UTF-8"):
IMPORTANT: The exception will be triggered on the receiving server, not on the client running the SendAsync. (EDITED)
System.Net.WebSockets.WebSocketException (0x80004005): The WebSocket message's payload or field contained invalid data where UTF-8-encoded text was expected.
at System.Net.WebSockets.ManagedWebSocket.CloseWithReceiveErrorAndThrowAsync(WebSocketCloseStatus closeStatus, WebSocketError error, String errorMessage, Exception innerException)
at System.Net.WebSockets.ManagedWebSocket.ReceiveAsyncPrivate[TResult](Memory`1 payloadBuffer, CancellationToken cancellationToken)
at System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder`1.StateMachineBox`1.System.Threading.Tasks.Sources.IValueTaskSource<TResult>.GetResult(Int16 token)
at System.Threading.Tasks.ValueTask`1.ValueTaskSourceAsTask.<>c.<.cctor>b__4_0(Object state)
--- End of stack trace from previous location ---
Actual behavior
IMPORTANT: The exception will be triggered on the receiving server, not on the client running the SendAsync. (EDITED)
System.Net.WebSockets.WebSocketException (0x80004005): An exception caused the WebSocket to enter the Aborted state. Please see the InnerException, if present, for more details.
at System.Net.WebSockets.ManagedWebSocket.CloseWithReceiveErrorAndThrowAsync(WebSocketCloseStatus closeStatus, WebSocketError error, String errorMessage, Exception innerException)
at System.Net.WebSockets.ManagedWebSocket.ReceiveAsyncPrivate[TResult](Memory`1 payloadBuffer, CancellationToken cancellationToken)
at System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder`1.StateMachineBox`1.System.Threading.Tasks.Sources.IValueTaskSource<TResult>.GetResult(Int16 token)
at System.Threading.Tasks.ValueTask`1.ValueTaskSourceAsTask.<>c.<.cctor>b__4_0(Object state)
--- End of stack trace from previous location ---
Regression?
No response
Known Workarounds
No response
Configuration
.NET 8 on Windows. I don't believe it is OS- or hardware-specific.
Other information
No response
Activity
MihuBot commentedon Jun 9, 2026
cc: @dotnet/ncl
mattflaschen commentedon Jun 9, 2026
I understand that this is requesting a change to the public API surface, which would take some time (even if viewed favorably).
An interim improvement would be:
When constructing any
WebSocketExceptionusing the genericWebSocketError.Faulted(especially those without an inner exception), specify a custom error message, while leaving it asWebSocketError.Faulted.As an example: Protocol errors reported by
TryParseMessageHeaderFromReceiveBufferare already thrown withWebSocketError.Faultedand custom messages.I believe the default error message from auto-mapping
WebSocketErrorwill not be displayed in theToStringrepresentation if a custom message is passed to theWebSocketException. However, theWebSocketErrorCodewill still be available.MihaZupan commentedon Jun 10, 2026
IMO A reason to add enum values would be if you expected to programmatically react differently to different sorts of errors.
You wouldn't do that if you got an exception that the message isn't valid UTF8 - it indicates that your code was wrong, not something to react to on the fly.
We should, however, improve the error messages here, there's no reason we can't include them even with existing error codes.
Which particular flavour of protocol violation occurred doesn't matter, but getting a good exception message telling you what went wrong if you sent invalid UTF8 would be good.
mattflaschen commentedon Jun 11, 2026
@MihaZupan In the original issue, I didn't make an important point clear (now edited). Although my sample code intentionally sends invalid UTF-8 (as a reproduction), the encoding exception is on the receiving side (note it's in
ReceiveAsyncPrivate(orHandleReceivedCloseAsync, but I didn't provide a repro for that case)). (There is no encoding exception on the sending side, for my reproduction.)It's not a coding error on the computer (recipient) where the exception occurs. It's invalid data coming over the wire.
Therefore, I do think it's worth tracking the cause of the error with a code (
WebSocketError.InvalidEncodedText), if only for log analytics.I tend to agree with "Which particular flavour of protocol violation occurred doesn't matter". I think it's worth adding
WebSocketError.ProtocolError, but I don't think we need pinpoint codes for every specific protocol violation.I definitely agree that error messages can be updated right away (whether or not enum values are added later).