Recommended approach for handling errors across process using AIDL (Android) - java

I have a binder service and a client that live in different processes. Using AIDL, when the client calls into my remote binder service, there are times that I need to relay an error (exception) back to the client.
However, from my understanding, this is not possible. I tried throwing a "RemoteException" from my binder service to see what will happen, and I get
Uncaught remote exception! (Exceptions are not yet supported across processes.)
in my logcat.
Since it looks like this is not possible, what is the best approach for informing the client of an error? I was thinking I can just convert my AIDLs to use C-style interfaces in which I just return an error code (and 0 on success), but this looks ugly.
Is there a better approach?

Your remote method can return a Parcel that contains the result data or an Exception if there is an error. See the Parcel#writeException method. I believe that this is how Android exceptions make it back when performing actions on a ContentProvider that lives in another process. There are many ways to return the result data including using the Bundle class.
Your manager class can hide the implementation details by unparcelling and returning the data or throwing the unparcelled exception so users never interact with the Parcel.
Here is a link to the source for Parcel#writeException.

Related

How to analyse Websocket close reason 1011

First time using websockets. I have two machines that need to communicate using them. The server works fine, if I send a message with Postman, it replies correctly.
For the client I used one of the examples I found, like this. But in the client, when I create the WebsocketClientEndpoint :
final WebsocketClientEndpoint clientEndPoint =
new WebsocketClientEndpoint(new URI("ws://myserver.com/endpoint"));
it calls the onOpen and immediately after the onClose, returning a 1011 close reason, that I read is an unexpected condition in the server.
I would need some clue to analyse what can be happening, because as I said, the server replies well in Postman. The url is the same, of course. The examples I find are quite identical, and I am not doing anything different. Any idea?
My fault. As indicated by user207421, I should have checked what was really arriving to the server. The client was not sending hardcoded data. I was sending a JSON to it and it was forwarding it to the server. That server replied well to the same JSON if sent directly. The thing was that the client, in the deserialization and serialization, was sending the final reconstructed JSON with a missing field, and that made the server fail to reply. As dumb as that. The risk of assuming things.
First, I would recommend not to try to instantiate an instance of WebsocketClientEndpoint() as the only implementation of the class I can find uses static connect() methods, which require either an existing instance of WebSocketClient() or WebSocketContainer() - See this example. Instead, I would recommend creating a class that extends WebSocketClient and work with that instead - see an implementation of that here.
Also, another thing that might cause a different sort of problem is the possibility of an Unhandled Exception causing code execution to prematurely abort. The URI class throws a URISyntaxException, and if you are not wrapping your new URI object instantiation in a try/catch block or denoting the current scope method/class as throws URISyntaxException (or throws Exception to handle the other exceptions that might be thrown by WebsocketClient() as well) and have the thrown Exception(s) handled in a try/catch block in outer calling context, your code may be crashing due to that.

How to deal with wrong ids of resource in REST API?

I have the following method in my service layer.
public void delete(int candidateId) {
candidateRepository.delete(candidateId);
}
Pretty basic, now this method is used by the web layer which RESTful architecure is applied.
The URL that will trigger this method is:
DELETE /candidates/{id}
How should I deal with wrong ids given by the clients that use the REST API in the service layer? I know the HTTP response would be 4xx but how should I communicate that the id is invalid between the service and web layer?
Should I use a unchecked exception since this is a condition that my application is unable to recover from? The fault barrier (Spring exception handler) will deal with it.
Or should this be a checked exception since it is possible that clients give wrong ids?
I am using the latest Spring technology if that matter
If it is possible that clients give wrong ids, then they will give wrong ids. And this is a condition that your application should be able to recover from.
I would return a checked exception for this. But introducing a checked exceptions can sometimes mean changes throughout different layers of the application, because, for example, the signatures of many methods would need to be changed to add the "throws" clause (breaking OCP). In case that gets overcomplicated some people (like in Robert C. Martin's "Clean Code") recommend using unchecked exceptions. I would say it's up to you what to return as long as the exception has a meaningful description.
Firstly, you need to decide how your REST API will handle exceptions. There are multiple, equally valid solutions to this.
When designing an API, you pretty much have to assume that whatever can go wrong, will go wrong. Client applications will pass incorrect parameters, use incorrect formats, etc.; your application should expect this, and handle it gracefully.
Using exceptions to communicate business logic is not particularly readable, and may have performance implications. It really doesn't scale beyond very simple cases - imagine that the business logic for "delete" might need to include failures for "record not found", "record has dependent relationships", "record protected", "record archived" etc.
Instead, I would design the application to pass explicit status information back and forth, and translate this into whatever RESTful error handling you use.

android connection exception/lost manager

Background
So I've inherited an android application that in various places connects to web services to send or receive information.
As it is right now, when a connection fails the user of the android device is prompted with an error message that for most users are viewed as obscure.
The problem
So what I'm looking for is a pattern or suggestion on how to implement a solution in this android application that catches all java connection exceptions and presents a dialog telling the user he lost the internet connection and needs to try again.
Any ideas? :-)
Edit, current idea
My current idea to solve this issue, or making it a bit more managed instead of having a fractured exception handling that takes care of the problem at every possible connection is this.
Each communication instance/class will inherit from a super class, or implement an interface that forces this class to be used. This class contains the logic for connection exceptions. Lets just for now call it ConnectionExceptionManager.
The problem then only becomes implementation of this in each communication class in each web service call. In each web service calls exception I need to check for communication exceptions and if it hits, use the ConnectionExceptionManager in this catch.
This would however still make it a hassle, to copy into request method in each communication class.
Any ideas about improving this current idea of mine?
What I understood from your question is that you need to check internet connectivity before performing any internet related action. For that you can simply create public static boolean function i.e. public static boolean isInternetConnected(){...} in global class so that you can reuse your function.
If you want your application to check internet connectivity automatically then you can use IntentService which will work in background and in its protected abstract void onHandleIntent (Intent intent) you can check isInternetConnected() returns true and if not then you can open AlertDialog.
To use this background service after repeated intervals while application is running, you can use AlarmManager.
Hope this helps.

Java Throwing exceptions vs returning response in catch

I know a lot has been discussed around exception handling, however I need some advice specific to my situation.
I am currently working on a Spring MVC application with Controller->Services->DAO layers. The service classes catch mainly two kinds of exceptions HibernateException and IOException.
HibernateException because service needs to perform rollback if a transaction did not succeed and IOException since it is an unchecked exception and needs to be caught or thrown and I prefer the first option.
Now what would be a better way of handling these further up in the stack :
Should I rethrow these exceptions to the controller and in the
ExceptionHandler of the controller send a HTTP error-code 500
Or in the catch block create the normal JSON response object, setting status=failure and the appropriate error message and return this to the Controller?
Exception Handling convensions:
There is a saying that, best way of handling Exception is not to handle it!
For Spring's convention of controller<->service<->dao layers, Exception handling mechanism is known as Bubble up. Any exception occurs in the dao or service layer, you should pop it up to the controller layer (by adding throws XXXException in dao and service layer's method signature, is the most common way). Only controller layer should handle Exceptions.
Here is a nice tutorial of how you can handle exceptions for REST with spring.
Send HTTP Status code 500 or JSON object with status:
Sounds like you are writing API with Spring MVC. Look, when you are writing API's you should follow the proper conventions. It is Globally accepted that for internal server errors you send HTTP response with code 500, that means internal server errors.
There are number of causes for what you should not send JSON response in this case. One of the main cause is the implicit assumption of your API client. That is HTTP response with code 200 with a JSON object means every thing went normal. And thus the client side business logic may reflect that assumption which is wrong eventually.
Here you can see some API error code conventions for some well-known organizations:
twitter
LinkedIn
Facebook Graph API
I assume that you have not come so far yet as to create a client and therefor can pick 100% for yourself.
If so I would also recommend to use 1, for the main reason that using the correct status codes can go a long way in your API, as well as it's a very easy solution to your problem. You can write some neat code for your error handling.
Another major reason why you should use your first point is because you can easily re-use the error handling for other APIs, resources or webapps.
For example an enum with all your errors, and what status code you consider them to be, and you can also include what log level you want them to be.
public enum ExceptionMapping {
IllegalArgumentException(IllegalArgumentException.class, 400, LogLevel.ERROR),
If your goal is to build a neat API for unknown clients I would recommend reading more about REST level 3 (http://martinfowler.com/articles/richardsonMaturityModel.html) where you includes hypermedia links to create an API which allows the client to "browse" your full API. It's more work for the client since they have to be smarter but it can provide you with very nice features such as breaking a large part of your API without the client even noticing.

Pausing and notifying particular threads in a Java Webservice

I'm writing a Java webservice with CXF. I have the following problem: A client calls a method from the webservice. The webservice has to do two things in parallel and starts two threads. One of the threads needs some additional information from the client. It is not possible to add this information when calling the webservice method, because it is dependent from the calculation done in the webservice. I cannot redesign the webservice becuase it is part of a course assignement and the assignements states that I have to do it this way. I want to pause the thread and notify it when the client delivers the additional information. Unfortunately it is not possible in Java to notify a particular thread. I can't find any other way to solve my problem.
Has anybody a suggestion?
I've edited my answer after thinking about this some more.
You have a fairly complex architecture and if your client requires information from the server in order to complete the request then I think you need to publish one or more 'helper' methods.
For example, you could publish (without all the Web Service annotation):
MyData validateMyData(MyData data);
boolean processMyData(MyData data);
The client would then call validateMyData() as many times as it liked, until it knew it had complete information. The server can modify (through calculation, database look-up, or whatever) the variables in MyData in order to help complete the information and pass it back to the client (for updating the UI, if there is one).
Once the information is complete the client can then call processMyData() to process the complete request.
This has the advantage that the server methods can be implemented without the need for background threads as they should be able to do their thing using the request-thread supplied by the server environment.
The only caveat to this is if MyData can get very large and you don't want to keep passing it back and forth between client and server. In that case you would need to come up with a smaller class that just contains the changes the server wants to make to MyData and exclude data that doesn't need correcting.
IMO it's pretty odd for a web service request to effectively be incomplete. Why can't the request pass all the information in one go? I would try to redesign your service like that, and make it fail if you don't pass in all the information required to process the request.
EDIT: Okay, if you really have to do this, I wouldn't actually start a new thread when you receive the first request. I would store the information from the first request (whether in a database or just in memory if this is just a dummy one) and then when the second request comes in, launch the thread.

Categories