I have a three-tier architecture and send some data at the transport level (TCP Client) using tcp sockets, this is asynchronous using the BeginSend method.
public void TransportData(Stream stream) { try { SetTransporterState(StateObject.State.SendingData); if (clientSock.Connected) { ASCIIEncoding asen = new ASCIIEncoding(); stream.Position = 0; byte[] ba = GetStreamAsByteArray(stream); if (clientSock.Connected) clientSock.BeginSend(ba, 0, ba.Length, SocketFlags.None, new AyncCallback(SendData), clientSock); else throw new SockCommunicationException("Socket communication failed"); } catch (SocketException sex) { throw sex; } catch (SockCommunicationException comex) { bool rethrow = ExceptionPolicy.HandleException(comex, "TransportLayerPolicy"); if (rethrow) { throw; } } } } catch (SocketException soex) { throw soex; } catch (SockCommunicationException comex) { bool rethrow = ExceptionPolicy.HandleException(comex, "TransportLayerPolicy"); if (rethrow) { throw; } } catch (Exception ex) { LoggingMessageHelper.LogDeveloperMessage(ex.Message + Environment.NewLine + ex.StackTrace, 1, TraceEventType.Critical); bool rethrow = ExceptionPolicy.HandleException(ex, "TransportLayerPolicy"); if (rethrow) { throw; } } }
SendData () callback code is below
private void SendData(IAsyncResult iar) { Socket remote = null; try { remote = (Socket)iar.AsyncState; try { int sent = remote.EndSend(iar); } catch (Exception ex) { throw ex; } if (remote.Connected ) { remote.BeginReceive(data, 0, size, SocketFlags.None, new AsyncCallback(ReceiveData), remote); } else throw new SockCommunicationException("Communication Failed"); } catch (SocketException soex) { throw new SockCommunicationException("Communication Failed"); } catch (SockCommunicationException comex) { bool rethrow = ExceptionPolicy.HandleException(comex, "TransportLayerPolicy"); if (rethrow) { throw; } }
When the server shuts down, the client does not know until it sends some data, so the Connected property is true. Then the line remote.BeginReceive () throws a SocketException which I am trying to catch and throw a custom exception (sockCommunicationException).
However, when I do this, I get an unhandled exception. I would like to create this error for the user interface through the business layer. When a similar exception occurs in a callback method, where does it rise to?
How can I avoid this unhandled exception and throw this exception out of the user interface level.
Please, help.
Thanks in advance!
c # exception-handling asyncsocket
user466898
source share