I have a WCF service multiple UIs consume. When the user is unable to access the database, I get Unauthorised exception from the DB. I don\'t catch the exception on the server
You can use this code to create a wrapper class that will properly handle WCF exceptions:
public class ServiceProxyHelper : IDisposable
where TProxy : ClientBase, new()
where TChannel : class
{
///
/// Private instance of the WCF service proxy.
///
private TProxy _proxy;
///
/// Gets the WCF service proxy wrapped by this instance.
///
public TProxy Proxy
{
get
{
if (_proxy != null)
{
return _proxy;
}
else
{
throw new ObjectDisposedException("ServiceProxyHelper");
}
}
}
public TChannel Channel { get; private set; }
///
/// Constructs an instance.
///
public ServiceProxyHelper()
{
_proxy = new TProxy();
}
///
/// Disposes of this instance.
///
public void Dispose()
{
try
{
if (_proxy != null)
{
if (_proxy.State != CommunicationState.Faulted)
{
_proxy.Close();
}
else
{
_proxy.Abort();
}
}
}
catch (CommunicationException)
{
_proxy.Abort();
}
catch (TimeoutException)
{
_proxy.Abort();
}
catch (Exception)
{
_proxy.Abort();
throw;
}
finally
{
_proxy = null;
}
}
}
You can then call a service like this:
using (ServiceProxyHelper svc =
new ServiceProxyHelper())
{
svc.Proxy.SendMail(fromAddress, fromName, toEmail, toName, message);
}