Reputation: 789
I have a PHP RESTful API, which returns JSON objects. I have an Android client requesting REST requests from that API
Till now if there was a problem in the server side then the API returned a booleanic response "false"
I want to change the flow of the API, so instead of sending a JSON response containing "false" it will throw and Exception, and I want the android side to catch the exception.
So basically, i want something like the following Android code:
try {
php_api.getUsers();
} catch (Exception ex) {
// TODO
}
Can it be done? Will any PHP exception be caught in this way?
Upvotes: 0
Views: 768
Reputation: 1881
I haven't worked with Java but I don't think that you can do that. When PHP throws an exception, it will still produce an output of some sort, depending on how you set up exception handling. It could show the exception message with a stack trace or something similar. But on the client (your Java app) side, this is nothing more than text.
However, a rest response should always have headers that you can check. Take a look at this: http://blog.zenika.com/index.php?post/2011/05/18/Error-handling-with-REST
By following what is written there, your Java-to-PHP api would always read the response headers before returning the content. If a 500 or 400 showed up, you'd throw a java exception from the api which you could catch in the code that uses it.
If your PHP side is not sending the headers you want, you can always override PHP's error/exception handling to produce custom output (including headers).
Upvotes: 1