我搜索了很多链接,但实际上没有任何链接,而且大多数链接都没有提供正确的客户端代码。我缺少一些东西。
我有下面的异常类
[DataContract]
public class MyException
{
public MyException(Exception ex)
{
Message = ex.Message;
StackTrace = ex.StackTrace;
ExceptionType = ex.GetType();
}
[DataMember]
public string Message { get; set; }
[DataMember]
public string StackTrace { get; set; }
//[DataMember]
// This is having issues. On client side WebException.Response is null
//public Type ExceptionType { get; set; }
}
我的界面如下所示
[OperationContract]
[WebInvoke(
Method = "POST",
UriTemplate = "/Documents/getallunprinteditems",
BodyStyle = WebMessageBodyStyle.Bare,
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json
)]
MyResponse MyMethod(MyRequest request);
我的实现如下所示
public MyResponse MyMethod(MyRequest request)
{
try
{
...
// for testing created a dividebyzero exception
}
catch(Exception ex)
{
MyException ex = new MyException(ex);
throw new WebFaultException<MyException>(ex,
System.Net.HttpStatusCode.HttpVersionNotSupported);
}
}
我在客户端有以下代码,但是它总是可以捕获Exception块。我想念的是什么?
try
{
MyRequest upRequest = new MyRequest();
....
MyResponse upResponse = new MyResponse();
string url = "http://localhost:2023/myservice/getdata";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json";
byte[] data = Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(upRequest));
request.ContentLength = data.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();
WebResponse response = request.GetResponse();
Stream respStream = response.GetResponseStream();
StreamReader reader = new StreamReader(respStream);
string responseData = reader.ReadToEnd();
Newtonsoft.Json.JsonConvert.PopulateObject(responseData, upResponse);
......
}
catch (System.ServiceModel.Web.WebFaultException<MyException> ex)
{
throw ex;
}
//below is just for test purpose...
catch (System.ServiceModel.FaultException<MyException> ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
更新: How to Handle WebFaultException to return CustomException?
我在客户端添加了以下内容,而且很成功。
catch (WebException ex)
{
if(ex.Response != null)
{
string errorString = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
MyException ex1 = new MyException();
Newtonsoft.Json.JsonConvert.PopulateObject(errorString, ex1);
}
}
解决方案:
问题在于下面的属性
[DataMember]
public Type ExceptionType { get; set; }
ErrorDetails必须是可序列化的对象,并且看起来不是Type。