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

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.

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.

to service response context or not

when calling a state changing service e.g.
void SaveCustomer(Customer customer)
the following may happen
the parameters are invalid
an exception occurs
authorisation is not successful
a business rule(s) is violated
everything is ok
For conditions 1-3 I think the service should return an appropriate exception
For #4 I also think the service should return an exception but some believe it should return an object that reflects the success or otherwise of the call (a response object).
In our case a business rule violation is an opportunity for an end user to choose an alternative action. I think a custom exception that lists error codes can be parsed by a client and localised. A response object can do the same but in a more strongly typed way.
With a response object we need to cater for a path back up the stack to the service (if(ok) etc) and we can't rely on an exception unwiniding a transaction.
Is either of these options an anti-pattern?
There is also third approach not mentioned by your listing. The approach is called expected exception. Request-response operations in web services offers definition of three types of messages:
Input = request. Can be defined only once for each operation.
Output = successful response. Can be defined only once for each operation.
Fault = expected unsuccessful response. You can have zero or more faults defined for each operation.
When using faults you tell client that the operation can fail due to some well defined reason. For example incomplete customer definition and client can handle this fault in different way than common unexpected SOAP fault.
In WCF expected faults are handled through FaultContract and generic FaultException<>. Check this article and its subarticles for introduction to fault handling.
The implementation of error handling is mostly up to you. Returning custom object is especially helpful in complex scenarios where the operation can succeed only partially and you must report both success and parts which failed.

Handling ObjectDisposedExceptions on disconnected WCF channels

When a method is called on a WCF channel that has been disconnected for some reason, it raises an ObjectDisposedException.
Now is normal operation this should not happen, but if for some reason it did, I would like to be able to handle the exception nicely by showing an error to the user like "An operation failed because the service is not connected".
The problem is I just get a generic disposed exception in my appwide exception handler, so I have no way of determining whether WCF threw it.
to get around this I currently have a wrapper class that simply wraps all service method calls with try/catch and rethrows any ObjectDisposedException's as a custom comms exception that my global handler can deal with. this is a load of boilerplate stuff I could do without though.
Is there any way of determining whether WCF threw the exception?
Cheers
I used to encounter such problem, it seems it's difficult to determine whether the WCF throws exception. You can't use the CommunicationObject.Status for this problem, only when you try to use that channel, it throws exception to tell you that the channel is faulted.
Therefore, I used the way like yours.

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.

WCF - Overhead of throwing FaultExceptions within your service

I posted a question about using Messages versus Fault Exceptions to communicate business rules between services.
I was under the impression it carried overhead to throw this exception over the wire, but considering it's just a message that get serialized and deserialized, they were in fact one and the same.
But this got me thinking about throwing exceptions in general or more specifically throwing FaultExceptions.
Now within my service, if i use
throw new FaultException
to communicate a simple business rule like "Your account has not been activated",
What overhead does this now carry?
Is it the same overhead as throwing regular exceptions in .NET? or does WCF service handle these more efficiently with the use of Fault Contracts.
So in my user example, which is the optimal/preferred way to write my service method
option a
public void AuthenticateUser()
{
throw new FaultException("Your account has not been activated");
}
option b
public AutheticateDto AutheticateUser()
{
return new AutheticateDto() {
Success = false,
Message = "Your account has not been activated"};
}
Well... In general you shouldn't be throwing exceptions for expected conditions, or anything you expect to happen regularly. They are massively slower than doing normal methods. E.g., if you expect a file open to fail, don't throw a that exception up to your caller, pass the back a failure code, or provide a "CanOpenFile" method to do the test.
True, the message text itself isn't much, but a real exception is thrown and handled (possibly more expensively because of IIS), and then real exception is again thrown on the client when the fault is deserialized. So, double hit.
Honestly, if it is a low volume of calls, then you probably won't take any noticeable hit, but is not a good idea anyway. Who wants to put business logic in a catch block :)
Microsoft : Exceptions And Performance, & Alternatives
Developer Fusion: Performance, with example
It's just like a normal exception, and uses the same wrapping code as a normal exception would to marshal into a fault, including unwinding the stack.
Like exceptions SOAP faults shouldn't, to my mind, be used for program flow, but to indicate errors.