How to Catch Exceptions thrown by a WCF service In Client

You can easily get the server side Unhandled exceptions thrown by a WCF service in Client by using FaultException

Set includeExceptionDetailInFaults to true in your service behaviours

<serviceBehaviors>
<behavior name=””>
<serviceMetadata httpGetEnabled=”false” />
<serviceDebug includeExceptionDetailInFaults=”true” />
</behavior>
</serviceBehaviors>

and then in client side you can catch exceptions like below
try
{
//your service call
}
catch (FaultException ex)
{
string msg = "FaultException: " + ex.Message;
MessageFault fault = ex.CreateMessageFault();
if (fault.HasDetail)
{
System.Xml.XmlReader reader = fault.GetReaderAtDetailContents();
if (reader.Name == "ExceptionDetail")
{
var detail = fault.GetDetail<Exception>();
msg += "\n\nStack Trace: " + detail.StackTrace;
}
}
//TraceService.Trace(msg);
}

Enjoy Programming…

The request was aborted: The connection was closed unexpectedly

I got a exception while sending a mail that The request was aborted: The connection was closed unexpectedly.  I don’t know why it is happening.. After some researching i got a point that this is because i am disposing  http response object before reading from its stream.

Code i got exception
using(Stream stream = req.GetResponse().GetResponseStream()){
if (stream != null)
{
attachment = new Attachment(stream, ct);
message.Attachments.Add(attachment);
}
}

Send mail after disposing the stream object
client.Send(message);

Solution

Don’t try to pass the stream object after disposing. The using statement obtains the resource specified, executes the statements and finally calls the Dispose method of the object to clean up the object.
Corrected Code

using(Stream stream = req.GetResponse().GetResponseStream()){
if (stream != null)
{
attachment = new Attachment(stream, ct);
message.Attachments.Add(attachment);
client.Send(message);
}
}

Enjoy coding…