WCF Call Result
What would be a better approach when providing a wcf client with the call result.
1. Wrapping the result in an object
public enum DefinedResult : short {
Success = 0,
TimeOut = 1,
ServerFailure = 2,
UserNotFount = 3,
Uknown = 4,
//etc.
}
[DataContract]
public class ServiceResult {
readonly DefinedResults dResult;
public ServiceResult(DefinedResult result) {
this.dResult = result;
}
[DataMember]
public bool IsSuccess
{
get {return this.dResult == DefinedResult.Success;}
}
}
//Client:
WcfClient client = new WcfClient();
ServiceResult result = client.DoWork();
2. Throwing a custom Exception:
[Serializable]
public UserNotFoundException: Exception {
public UserNotFoundException(string message): base(message) {}
}
//client:
WcfClient client = new WcfClient();
try {
result = client.DoWork();
}
catch(FaultException<ExceptionDetail> ex) {
switch(ex.Detail.Type)
{
case "MyCompany.Framework.Exceptions.UserNotFound":
//handle
break;
case "MyCompany.Framework.Exceptions.ServerError":
//handle
break;
}
}
Now, the client can be another .net process (server side) or the same service can be called by java script, hence the question - which one of these (or may be there is something better) is a better approach to let the client know of what happened with the 开发者_Python百科call?
First of all, it depends: if you want to return a condition which is not exceptional, then use a result value. Otherwise, use exceptions. In WCF, it goes like this:
Create a custom exception class:
[DataContract]
class MyException : FaultException<mydetails>
Define that your service throws it:
[FaultContract(...)]
void mymethod()...
throw MyException
in your service method
Then you can catch your exception in the service method like catch FaultException<mydetails>
This is the nicest way there is.
FaultExceptions are swallowed by WebHttpBinding (required for JSON/REST services). In this case, if you want to provide detailed infos to your client, Option 1 is better.
If JSON is not in the way, I would recommend Option 2.
精彩评论