to service response context or not - wcf

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.

Related

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.

Approach to pass validation result, on failure, from WCF service (with EF4 data processing) to MVC3 client

I implement a ASP.NET MVC3 application, where data is accessed through WCF services.
The WCF service uses EF4.1 for data access with DBContext and POCO classes for entities.
I can annotate the properties with data validations attributes on the server side, and also I can implement custom validation by defining either custom validation attributes (derived from ValidationAttribute), or by implementing IValidatableObject ).
But I have a problem: if validation fails, what is the best approaoch to pass validation error info from WCF to client, and then use it in MCV3 client?
As I understand with WCF, every data exchanged between client and WC service should be part of the data contract, and should not use exceptions as ways of passing meaningful information between server and client (like throwing a ValidationException with extra properties set for Validation failure info).
Also in WCF who uses EF I call dbContext.SaveData(), but if data is not valid, it throws exception, which I don't want.
So:
how can I call validation explicitly in EF and make sure either the object is valid and I can call SaveData(), or the object is invalid and I can collect somehow validation failure information to pass to client.
Haw can I pass this validation failure information back to client, as part of data contract, and not an an exception.
Thanks
You can use two approaches:
Use standard response data contract for success and fault contract with FaultException<YourFaultContract> for validation failure. Typed fault exceptions are way to define "expected" exceptions - it is just another data contract passed in SOAP Fault describing some failure.
Create response data contract which contains something like result code, response data, failure message etc. and use this data contract for both success and failure. I don't like this approach but it is easier to use in some ESB where faults are processed in special way.

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.

Implement 'Ping' functionality using Message Inspector causes WCF runtime to throw NullReferenceException

I'm using WCF to implement a web service. This web service requires a 'ping' feature as a health monitor for each service. This functionality has been implemented using IDispatchMessageInspector and is configured for each endpoint of a service. This is due to a business requirement for the 'ping' to be as near the actual service code as possible. At the same time, I did not want to tie it to each service implementation's code and IDispatchMessageInspector seems to be a good fit.
The service uses a Request-Reply MEP. Each request message contains an element that specifies what processing is required. The service will then use this value to determine how to process the data in the message. The same element is used to define a request message as a 'heartbeat' check.
The 'ping' message inspector will pre-process a request message in the AfterReceiveRequest() method and if it determines the request is a 'heartbeat', it will then generate the correct response and pass that on to the BeforeSendReply() method via a correlation object returned from AfterReceiveRequest(). The request message parameter of AfterReceiveRequest(), which is by reference, is then set to null to prevent the message from being processed by the service implementation code.
The technique of setting request message to null was found in a web site or blog which I can't remember nor find the URL for. This technique works great on it's own and I can prevent service implementation code from being executed if it's a 'heartbeat' request.
Unfortunately, setting the request message to null in a message inspector will cause the WCF runtime to always throw a NullReferenceException. From the stack trace, I gather the runtime will still pass the message object (which will be null after going through 'Ping' message inspector) to the dispatcher and when the dispatcher tries to deserialise a null message object, causes the NullReferenceException.
However, my system also implements IErrorHandler to catch any unhandled exceptions in the service and log it. This means every successful 'heartbeat' request will generate a log entry for the NullReferenceException and the 'heartbeat' could be as frequent as every minute.
The Question :
What can I do to prevent logging of 'useless' NullReferenceException thrown when 'Ping' prevents service implementation code from running by setting request to null.
Many thanks in advance.
~hg
Not the most graceful solution but potential workarounds (that i've not tested), but where you detect your ping calls in the inspector code, could you not throw your own custom exception type i.e. PingRequestException, and handle this when it returns to the client? Would that avoid you hitting the WCF Runtime code, thus avoiding the logging of unhandled exceptions.
Otherwise you could try to use a base service, inherited by all of your services (the other side of the wcf runtime code) that detects and handles ping requests in the constructor before hitting the actual service code.

Using Reqest / Response classes on a WCF contract - is that a good idea?

We have a situation where we might want to pass client information on every call we make on a WCF operation. At the response level, we want to have fields to indicate success and an error message.
Is it a good idea to use a Request class and a Response class? I was looking into two operation
OpeationResponseData Operation(OperationRequestData input);
I don't use OpeationRequest because that has issues with wsdl.
I will have base classes that will have the common fields each operation will need.
For example:
OperationResonseData : Response
OperationRquestData : Request
Another option is to use
Request<T> and Response<T>
I was wondering if there were a better way, or if there were some guidelines on this issue...
WCF's base messaging architecture, the Message class, already has support for all of these concepts built in.
For information that is supposed to be passed with each logical operation, you use headers.
For errors you throw FaultException or, if you want to return a custom data structure with your error, you throw FaultException. Being that errors result in faults, the lack of a fault indicates success. If you want to return details about your success then your operation should return a custom data type, otherwise you can just return void.
How this maps to what's sent across the wire depends on what formatting stack you're using (SOAP, REST, etc.). The default stack is SOAP and, being the blueprint for WCF, has a very natural mapping: headers map to SOAP headers and faults map directly to SOAP faults. For REST headers can be mapped as HTTP headers and faults would result in a 500 status with a message.