[WCF]DomainServices客户端操作异常处理

时间:2021-08-31 08:31:02

作为个人备忘,不做排版。此扩展函数用于DomainServices的Load及SubmitChanges时处理Error信息,包括验证消息、实体冲突。

 1 public static string ToErrorString(this System.ServiceModel.DomainServices.Client.OperationBase op)
2 {
3 //来自http://www.cnblogs.com/ainijiutian/p/3616198.html
4 if (op.HasError)
5 {
6 op.MarkErrorAsHandled();
7
8 System.Text.StringBuilder sb = new System.Text.StringBuilder();
9 if (op is System.ServiceModel.DomainServices.Client.LoadOperation)
10 {
11 var lo = op as System.ServiceModel.DomainServices.Client.LoadOperation;
12 if (lo.ValidationErrors != null && lo.ValidationErrors.Any())
13 {
14 sb.Append("Validation Errors:\r\n" + string.Join("\r\n", lo.ValidationErrors.Select(t => t.ErrorMessage)) + "\r\n\r\n");
15 }
16 sb.Append("Error message:\r\n" + lo.Error.ToString());
17
18 return sb.ToString();
19 }
20 else if (op is System.ServiceModel.DomainServices.Client.SubmitOperation)
21 {
22 var so = op as System.ServiceModel.DomainServices.Client.SubmitOperation;
23 if (so.EntitiesInError != null && so.EntitiesInError.Any())
24 {
25 foreach (var e in so.EntitiesInError)
26 {
27 sb.Append(so.EntitiesInError.First().GetType() + " " + e.ToString() + ":\r\n");
28 if (e.HasValidationErrors)
29 {
30 sb.Append("Validation Errors:\r\n" + string.Join("\r\n", e.ValidationErrors.Select(t => t.ErrorMessage)) + "\r\n");
31 }
32 if (!e.EntityConflict.IsDeleted && e.EntityConflict != null && e.EntityConflict.PropertyNames != null && e.EntityConflict.PropertyNames.Any())
33 {
34 sb.Append("Entity conflict:\r\n" + string.Join(", ", e.EntityConflict.PropertyNames) + "\r\n");
35 }
36 }
37 sb.Append("\r\n");
38 }
39 sb.Append("Error message:\r\n" + so.Error.ToString());
40 //if (sb.ToString().Contains("STAMP")) //timestamp
41 //{
42 // return "Document has been changed in other place,please undo the current changes and reopen .";
43 //}
44 //else
45 //{
46 // return sb.ToString();
47 //}
48 return sb.ToString();
49 }
50 }
51 return op.ToString();
52 }