Skip to content

Web Sockets: WebSocketError.Faulted is uninformative: Add and use ProtocolError and InvalidEncodedText #129192

Closed

Description

@mattflaschen

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:

  1. ReceiveAsyncPrivate - TryParseMessageHeaderFromReceiveBuffer failure:
  • Currently - WebSocketError.Faulted, with specific message and no inner exception.
  • Could be new WebSocketError.ProtocolError, which mirrors WebSocketCloseStatus.ProtocolError. Can not be WebSocketError.HeaderError, since that is defined to refer to HTTP-level headers, not within-protocol WebSocket headers.
  1. ReceiveAsyncPrivate - Payload not valid UTF-8:
  • Currently WebSocketError.Faulted, with no specific message or inner exception.
  • I recommend a new WebSocketError.InvalidEncodedText.
  1. 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)
  1. 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).
  1. HandleReceivedCloseAsync - Failed to decode close status description as valid UTF-8:
  • Currently WebSocketError.Faulted, with an inner DecoderFallbackException, 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

  1. MihuBot commented on Jun 9, 2026

    @MihuBot

    cc: @dotnet/ncl

  2. mattflaschen commented on Jun 9, 2026

    @mattflaschen
    Author

    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 WebSocketException using the generic WebSocketError.Faulted (especially those without an inner exception), specify a custom error message, while leaving it as WebSocketError.Faulted.

    As an example: Protocol errors reported by TryParseMessageHeaderFromReceiveBuffer are already thrown with WebSocketError.Faulted and custom messages.

    I believe the default error message from auto-mapping WebSocketError will not be displayed in the ToString representation if a custom message is passed to the WebSocketException. However, the WebSocketErrorCode will still be available.

  3. MihaZupan commented on Jun 10, 2026

    @MihaZupan
    Member

    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.

  4. added
    untriaged
    on Jun 10, 2026
  5. mattflaschen commented on Jun 11, 2026

    @mattflaschen
    Author

    @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 (or HandleReceivedCloseAsync, 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).

  6. added this to the 11.0.0 milestone on Jun 15, 2026
  7. removed
    untriaged
    on Jun 15, 2026
  8. locked and limited conversation to collaborators on Jul 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions