WCF Response Class Best Practices - wcf

I'm not sure if there's a best practice for Response Message in WCF. Could anyone please guide me to right direction please?
I've a BlaResponse Object with following attributes:
1. dateTime
2. sucessfailureMessage.
is there anything else I need to add e.g. number of errors, details of errors. Number of success correlationID etc etc?
Thank you in advance.

Why do you have such attributes. You must have some real requirement for introducing these parameters in your response - for example response grouping both successful and failed operations. If your response is just for single operation you should get rid of that and use exceptions for propagating faults.
WCF has very big support for typed exceptions - FaultContracts. You can create special FaultContract type for any expected exception and throw it with typed FaultException. Client can catch each expected exception separately and handle it.

It is generally considered good practice to hide technical details of errors, or any information that discloses details about the server / architecture from the clients (unless you are debugging of course), as this might compromise your security.
It really depends what you are doing, so I don't think I can say what additional info you might need without more information about your implementation. Even the standard Fault Contract is pretty much just a wrapper for your own custom data.

Related

Can I inherit FaultException in WCF to throw custom faults?

Strangely I can't find anything on google for this. When doing regular exception stuff you'd create a MyCustomException : Exception and I assumed the same applied to ExceptionFaults.
When someone calls my service with an invalid api key, I wanted to throw an InvalidApiKeyExceptionFault. I can't seem to find an example online of how to set this up and have the client be able to catch it (presumably an attribute somewhere to include it into the WSDL).
Any suggestions where to look, or am I trying something that's not possible?
You should use FaultException<TDetail> and put your specific information in the serializable TDetail type.
Your service contract should have a fault contract specifying the TDetail type.
This technique enables you to communicate error information in an interoperable way, including to clients that know nothing about .NET exceptions.
If for some reason you don't want to use fault contracts, you could consider using the non-generic FaultException, and communicate additional information about the error in the fault reason and/or fault code / subcode.

WCF: use or not to use exception from service to client in production? any alternative?

I am thinking in use some exceptions to from service to client.
I am thinking for example in this case. The client try to insert a register in the database. This register has a value for e filed that exists in the database, and how it has a unique constraint, when I do the savechanges I get an updateException.
I am thinking to use exceptions (faultException) to warn to client of the error, and use a custom class to send to the client the actual data of the register, so in this way the client does not to make other query for the register.
However, in this link, it says that exceptions only should be used in development, no in production, so, without exceptions, how could I do what I want to do?
Perhaps I could use a custom class, that have one list property for each type of entities, and a property bool, that indicates if the operation is right or wrong, other property with an arbitrary code to indicate the type of error... etc. This is a good alternative?
In summary, really is better avoid exceptions in production? how I could communicate to the client errors from the service?
You have 2 options:
Throw exceptions and return WCF faults
Attach error information to you return objects
I personally favour throwing exceptions and returning WCF faults. I dont like the idea of attaching error information to return objects, I feel it violoates object oriented principals. For example a field called 'ErrorCode' has no place on a 'CustomerAddress' object.
I believe that if exceptional circustances arise, then an exception should be thrown. This will also simplfy your code as you wont have to wrap everything in try catch blocks in order to attach error information to your return object. Although you may want to catch unexpected exceptions and then throw a more appropriate exception with a more useful message.

Generic WCF Routing/Forwarding/Proxy Server

Is it possible to create a "generic" as in "adaptable" routing service, which will NOT have any public methods to call. Instead, you'd be able to call any command, which would then be mapped in the service and will pass it to appropriate end point with simple message transformation where required.
It may be hard to understand and idea might seem a bit crazy (it came from a colleague of mine), but it's clearer if you look at the example:
similar to what's described in this article, only difference is that our service should not have a "SubmitTimeSheet" public method, in fact it should have no public methods to call. We'd have to "intercept" an incoming call on a much lower level before it returns "Method Not Found" error.
Is this at all possible? The reason for this is obvious: possibility of adding new clients without having to change the code. All we'd have to do is to add a new mapping entry in some sort of config file or even database, e.g.
<Client address="newClientAddress" method="DoAnything" transformation="NewClientDoAnything.xslt" endPoint="endPointClientAddress" endPointMethod="endPointClientDoAnything" />
Check out WCF 4 routing - supports content based routing, xpath transforms and much more.
http://blogs.msdn.com/b/routingrules/
They have already done it in Nirvana. But it is very expensive.
This is not possible in WCF unless you define your contract as a very loose, fit-for-all contract which takes a message and returns a message. By doing this, you will los all the goodness (although not huge goodness in WCF) of WCF.

WCF IS One Way attribute

I am having a wcf method which has got isoneway attribute set to true.Now when i call this service from client ,service is throwing an invalid operation exception back to the client bcos of some business scenario going wrong.My understanding was that it will throw only endpointnotfound exception and timeoutexception.Can someone please explain why thats happening ?
Marking your contract as One-Way means exactly that: messages flow in one way only. Clients won't get an answer or wait for the service to execute at all, so there's no way that your client could possibly get a reply or fault from the service most of the time.
If you want that, then maybe a One-Way service isn't for you and what you really want is a two-way service with an empty reply (i.e. void)
Does the OneWay method return a value or has ref/out parameter? If yes, then that's the reason you are getting InvalidOperationException. This is expected behavior as per MSDN help for OperationContractAttribute.IsOneWay Property (http://msdn.microsoft.com/en-us/library/system.servicemodel.operationcontractattribute.isoneway(v=vs.110).aspx).
Look for remarks section, it has following text:
One-way methods must not return a value or have ref or out parameters; otherwise a System.InvalidOperationException exception is thrown.
PS: I know it's too late to reply to the thread, but for someone like me who stumbles across the post after 3 years or so, it might be useful.

Use Java exceptions internally for REST API user errors?

We have a REST API that works great. We're refactoring and deciding how to internally handle errors by the users of our API.
For example the user needs to specify the "movie" url parameter which should take the value of "1984", "Crash", or "Avatar". First we check to see if it has a valid value.
What would be the best approach if the movie parameter is invalid?
return null from one of the internal methods and check for the null in the main API call method
throw an exception from the internal method and catch exceptions in the main API method
I think it would make our code more readable and elegant to use exceptions. However, we're reluctant because we'd be potentially throwing many exceptions because of user API input errors, our code could be perfect. This doesn't seem to be the proper use of exceptions. If there are heavy performance penalties with exceptions, which would make sense with stack traces needing to be collected, etc., then we're unnecessarily spending resources when all we need to do is tell the user the parameter is wrong.
These are REST API methods, so we're not propogating the exceptions to the users of the API, nor would we want to even if possible.
So what's the best practice here? Use ugly nulls or use java's exception mechanism?
Neither.
The key is that passing a bad parameter isn't that exceptional a condition. Exceptions are thrown for exceptional circumstances. (That's the reason to not use them here, not the performance.)
You should be using something like Spring's DataValidation API for binding parameters that are passed in.
A client of a REST API should not be receiving null or exceptions. They should get an error message that gives them an idea of what's going on without exposing those details. "Sorry, we couldn't find that movie" or null? Go with the first, hands down.
If a invalid request came in (e.g. validation error) you should show 400 status code (bad request).
Internally I would also create an exception hierachy which maps to the HTTP Rest domain (see status codes for error cases).
Examples (simplified and being unchecked exceptions):
class RESTBaseException extends RuntimeException{
int statusCode;
public RESTBaseException(int statusCode){ this.statusCode=statusCode; }
//if no statusCode passed we fallback to very broad 500 server error.
public RESTBaseException(){ this.statusCode=500; }
}
class RESTValidationException extends RESTBaseException{
RESTValidationException(){
super(404);
}
}
you can extend above examples by also passing error messages to constructor to make client even more happy.
Later on you should catch these exceptions with a dedicated exception handler in your servlet handler chain (mapping status code to servlet response). For instance in spring mvc there are nice exception-handling solutions for that.
Usually I don't like to create a deep custom exception hierachies but I think for REST api layers they are OK (because the status codes are propagated later).
I will assume that you are doing input validation here and in this case, your database will do a query for a safe string and it won't find the record since it don't exist in your database, ok?
If you are using any MVC framework the Model should throw already a RecordNotFound exception no?
If you are always expecting to find a value then throw the exception if it is missing. The exception would mean that there was a problem.
If the value can be missing or present and both are valid for the application logic then return a null.
More important: What do you do in other places of the code? Consistency is important.