title: How to close the Websocket connection when an exception occurs and pass the exception message to the client?
body: <p><strong>Context:</strong></p>
  
  <p>We are using Websockets in our ASP.NET Core 2 MVC app. This is our code in our Startup.cs class:</p>
  
  <pre><code>public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  {
      [...]
  
      app.Use(async (context, next) =&gt;
      {
          if (context.WebSockets.IsWebSocketRequest)
          {
              if(context.Request.Path == "/ws")
              {
                  WebSocket lWebSocket =  await context.WebSockets.AcceptWebSocketAsync();
  
                  // a custom class that handles the websocket request → perhaps replace by an action controller.
                  var lHandleWebSocket = new HandleWebSocket();
  
                  await lHandleWebSocket.HandleConnection(context, lWebSocket);
              }
          }
      }
  }
  </code></pre>
  
  <p>The data transfer will be handled by the class 'HandleConnection':</p>
  
  <pre><code>public async Task HandleConnection(HttpContext context, WebSocket pWebSocket)
  {
      var lBuffer = new byte[1024 * 4];
      WebSocketReceiveResult lWebSocketReceiveResult = null;
      string lTmpString = string.Empty;
  
      // get next values
      lWebSocketReceiveResult = await pWebSocket.ReceiveAsync(new ArraySegment&lt;byte&gt;(lBuffer), CancellationToken.None);
  
      // Doing something here...
  
      // close connection
      await pWebSocket.CloseAsync(WebSocketCloseStatus.InternalServerError, "TestError", CancellationToken.None);
  }
  </code></pre>
  
  <p>Here is a small snippet about the used JavaScript:</p>
  
  <pre><code>self.WebSocketChat = new WebSocket("ws://" + window.location.host + "/ws");
  self.WebSocketChat.onclose = function (data) { console.log(data); }; 
  self.WebSocketChat.onerror = function (data) { console.log(data); };
  </code></pre>
  
  <p>Description: The client connects with the server. When the client sends the first message to the Server, then the server closes the connection. In the client the 'onclose'-event fires as expected and prints the following information to the console:</p>
  
  <pre><code>Console: CloseEvent {isTrusted: true, wasClean: true, code: 1011, reason: "TestError", type: "close", …}
  </code></pre>
  
  <p>All is working as expected. </p>
  
  <p><strong>Problem:</strong></p>
  
  <p>Now we want to close the websocket connection when an exception occurs on server-side. We want to pass the message and callstack of the exception into the closing frame.</p>
  
  <p>Catch Exceptions in the Startup.cs-File:</p>
  
  <pre><code>public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  {
      [...]
  
      app.Use(async (context, next) =&gt;
      {
          if (context.WebSockets.IsWebSocketRequest)
          {
              if(context.Request.Path == "/ws")
              {
                  WebSocket lWebSocket =  await context.WebSockets.AcceptWebSocketAsync();
  
                  // a custom class that handles the websocket request → perhaps replace by an action controller.
                  var lHandleWebSocket = new HandleWebSocket();
  
                  try
                  {
                      await lHandleWebSocket.HandleConnection(context, lWebSocket);
                  }
                  catch (Exception e)
                  {
                      // close connection
                      await lWebSocket.CloseAsync(WebSocketCloseStatus.InternalServerError, e.ToString(), CancellationToken.None);
                      throw;
                  }
              }
          }
      }
  }
  </code></pre>
  
  <p>Throw an exception:</p>
  
  <pre><code>public async Task HandleConnection(HttpContext context, WebSocket pWebSocket)
  {
      var lBuffer = new byte[1024 * 4];
      WebSocketReceiveResult lWebSocketReceiveResult = null;
      string lTmpString = string.Empty;
  
      // get next values
      lWebSocketReceiveResult = await pWebSocket.ReceiveAsync(new ArraySegment&lt;byte&gt;(lBuffer), CancellationToken.None);
  
      // throw an exception
      throw new TestException("TestException");
  }
  </code></pre>
  
  <p>When we send an message now to the server, the TestException will be thrown and catched as expected:</p>
  
  <p><a href="https://i.stack.imgur.com/3Iz5W.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3Iz5W.png" alt="enter image description here"></a></p>
  
  <p>But on client-side the 'onclose'-Event does not fire.</p>
  
  <pre><code>self.WebSocketChat.onclose = function (data) { console.log(data); }; // nothing happens
  </code></pre>
  
  <p>Also the '.onerror' event does not fire.</p>
  
  <p><strong>Question:</strong> </p>
  
  <p>How to close the Websocket connection when an exception occurs and pass the exception message to the client?</p>