示例(但将异常包装在FaultExceptions中,并添加FaultContractAttribute):
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.Sockets;
[OperationContract]
public void FetchImage(Uri url)
{
// Validate url
if (url == null)
{
throw new ArgumentNullException(url);
}
// If the service doesn't know how to resolve relative URI paths
/*if (!uri.IsAbsoluteUri)
{
throw new ArgumentException("Must be absolute.", url);
}*/
// Download and load the image
Image image = new Func<Bitmap>(() =>
{
try
{
using (WebClient downloader = new WebClient())
{
return new Bitmap(downloader.OpenRead(url));
}
}
catch (ArgumentException exception)
{
throw new ResourceNotImageException(url, exception);
}
catch (WebException exception)
{
throw new ImageDownloadFailedException(url, exception);
}
// IOException and SocketException are not wrapped by WebException :(
catch (IOException exception)
{
throw new ImageDownloadFailedException(url, exception);
}
catch (SocketException exception)
{
throw new ImageDownloadFailedException(url, exception);
}
})();
// Do something with image
}