Volley retry request - android-volley

I am currently testing out the volley library. But when request fails (404) it doesn't get executed again or at least there are no errors.However there is data missing. Is this the right way to retry a request if it has been failed ?
Thanks in advance
req.setRetryPolicy(new DefaultRetryPolicy(5000,1,1.0f));
queue.add(req);
Usage :
JsonObjectRequest req = null;
for(int i=0;i<profielen.size();i++){
final int pos = i;
req = new JsonObjectRequest(Request.Method.GET, imageLocUrl, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
setImageOnProfile(pos,response.get("thumbnail").toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
req.setRetryPolicy(new DefaultRetryPolicy(5000,1,1.0f));
queue.add(req);
}

No, that is not the right way.
Asides:
HTTP 404 is not a status code I would expect a normally-behaved HTTP
client under normal condition to retry.
You most like are receiving an error via the error listener you
supply to the request, but your error listener is a NOOP so maybe
you're not noticing?
(http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html has OK
descriptions of the status code meanings.)
The request's retry policy only applies to failures due to: open socket timeouts, socket opening timeouts, HTTP 401s and HTTP 403s. All other failures are not automatically retried, AFAIK.
I think that to retry a 404 with Volley you need to retry it by hand in onErrorResponse.
(Ficus: it would be nice if the RetryPolicy was consulted for error status codes. I would like to be able to set a policy that retries on 503s.)

Related

Laravel 9 HTTP client exception handling

I'm trying to catch errors that occur during HTTP client operations. If debugging is enabled APP_DEBUG=true then I get an error trace, if it is off, then it comes json response "message": "Server Error". But I need to catch exceptions, it doesn't work. Tried catch (\Illuminate\Http\Client\ConnectionException $e), but it didn't work. What am I doing wrong?
public function ExampleMethod()
{
try {
$response =
Http::withBasicAuth(env('REMOTE_LOGIN'), env('REMOTE_PASSWORD'))
->accept('application/json')
->retry(3, 2000)->timeout(12)
->withBody("dummy body content", "application/json")
->post($host . $url);
if ($response->ok()) {
//Do something
}
} catch (Exception $e) {
dd("CATCH IT");
}
}
There is an example from the documentation, the domain does not exist, and an exception handler should work somewhere, but it does not work
public function catchExceptins()
{
try {
$url = "domain-is-not-exist.com";
$response = Http::get($url);
if ($response->ok()) {
dd("200 OK");
}
//
if($response->failed()){
dd("FAILED");
}
//Below are the handlers that should work,
//but they do not respond when there is no domain
//or for example if the server response is 505
if($response->serverError()) {
dd("FAILED");
}
if($response->clientError()) {
dd("FAILED");
}
$response->throw(function($response, $e){
dd("FAILED");
})->json();
} catch (Exception $e) {
dd($e);
}
}
Laravel's HTTP client wrapper offers a mechanism for handling errors with a bunch of useful methods.
public function ExampleMethod()
{
try{
$response = Http::withBasicAuth(env('REMOTE_LOGIN'), env('REMOTE_PASSWORD'))
->accept('application/json')
->retry(3, 2000)->timeout(12)
->withBody("dummy body content", "application/json")
->post($host . $url);
//Check for any error 400 or 500 level status code
if($response->failed()){
// process the failure
}
//Check if response has error with 500 level status code
if($response->serverError()) {
//process on server error
}
//Check if response has error with 400 level status code
if($response->clientError()) {
//process on client error
}
// It also allows to throw exceptions on the $response
//If there's no error then the chain will continue and json() will be invoked
$response->throw(function($response, $e){
//do your thing
})->json();
}
catch(\Exception $e) {
//$e->getMessage() - will output "cURL error 6: Could not resolve host" in case of invalid domain
}
}
Laravel Docs - Http Client - Exception Handling
When you set APP_DEBUG=false, it just shows a generic error to the end user for security, but should give you the detailed error inside of the Laravel logs. 'All' APP_DEBUG=true does, is make the development process easier by displaying the log on the front end.
Your Laravel logs should be inside of "/storage/logs".
https://laravel.com/docs/9.x/configuration#debug-mode
https://laravel.com/docs/9.x/errors#configuration

spring boot DeferredResult onError how to invoke the callback?

Need to perform some asynchronous processing in a Rest service without holding up the server's Http threads .
I think DeferredResult would be a good option.
However when I am trying to ensure my callback on error gets called - am not able to do so .
Here is a naive attempt on my part:
#GetMapping("/getErrorResults")
public DeferredResult<ResponseEntity<?>> getDeferredResultsError(){
final String METHOD_NAME = "getDeferredResultsError";
logger.info("START : {}",METHOD_NAME);
DeferredResult<ResponseEntity<?>> deferredOutput = new DeferredResult<>();
ForkJoinPool.commonPool().submit(() -> {
logger.info("processing in separate thread");
int age = 0;
try {
age = age / 0;
}catch(Exception e) {
logger.error("we got some error");
logger.error(e);
throw e;
}
logger.info("after try catch block");
});
deferredOutput.onError((Throwable t) -> {
logger.error("<<< HERE !!! >>>");
deferredOutput.setErrorResult(
ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(t.getMessage()));
});
logger.info("done");
return deferredOutput;
}
When I call this Rest endpoint from Postman - I can see in server logs the arithmetic exception by zero but dont see the 'onError' getting invoked.
After some time get a response in Postman as follows:
{
"timestamp": "2019-07-30T09:57:16.854+0000",
"status": 503,
"error": "Service Unavailable",
"message": "No message available",
"path": "/dfr/getErrorResults"
}
So my question is how does the 'onError' get invoked ?
You need to pass the DeferredResult object to the asynchronous operation so you could update it in case of success or failure:
#GetMapping(value = "/getErrorResults")
public DeferredResult<ResponseEntity<String>> getDeferredResultsError() {
DeferredResult<ResponseEntity<String>> deferredResult = new DeferredResult<>();
ForkJoinPool.commonPool().submit(() -> {
System.out.println("Processing...");
int age = 0;
try {
age = age / 0;
deferredResult.setResult(ResponseEntity.ok("completed"));
}catch(Exception e) {
System.out.println("Failed to process: " + e.getMessage());
deferredResult.setErrorResult(
ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(e.getMessage()));
}
});
return deferredResult;
}
In the code you posted, you returned the DeferredResult object without passing it to the asynchronous operation. So after your return it, SpringMVC holds the client connection and wait until the DeferredResult object will be assigned with some kind of result. But in your case, the DeferredResult is not held by the asynchronous operation and will never updated so you get "Service Unavailable".
Here you can find working (light) project example.

IllegalStateException: response is not eligible for a body and must not be closed

sometimes we get this exception handling Response.
It seems that Response has a null body.
The code is something like:
try (Response response = client.newCall(request).execute()) {
// do stuff with the response
} catch (Exception e) {
log.error("Something wrong", e);
}
The exception is raised on the close() method automatically called on the Response, after the do stuff with response block went executed.
Stack trace:
java.lang.IllegalStateException: response is not eligible for a body and must not be closed
at okhttp3.Response.close(Response.java:281)
Are we missing something?
Thanks.
I think u can invoke response.body.close() which is the same as response.close(), and check body is null or not before close.
ResponseBody responseBody = null;
try {
Response response = client.newCall(request).execute();
responseBody = response.body();
// do stuff with the response
} catch (Exception e) {
log.error("Something wrong", e);
} finally {
if (responseBody != null) {
responseBody.close();
}
}
Since the Try with Resources works with Auto-closable (ie classes implement the Closable interface, it tries to call close automatically after the block.
Now the spec for Response close() method, does specify the method would throw and exception in certain cases.
It is an error to close a response that is not eligible for a body.
This includes the responses returned from {#link #cacheResponse},
{#link #networkResponse}, and {#link priorResponse()}.
Source:
https://github.com/square/okhttp/blob/master/okhttp/src/main/java/okhttp3/Response.java
So, it is 'expected' you can just log the details and continue if it is expected. OR handle appropriately (eg: retry) if it is not expected..

How to Disable zuul filter for specific condition case and not sending to mapped URL

I have zuul filter implementation with route config
related:
path: /api/search/related/**
url: http://abc.xyz.neverhit.this.URl
and run implementation
#Override
public Object run() {
RequestContext context = getCurrentContext();
HttpServletRequest request = context.getRequest();
UriComponents uri = UriComponentsBuilder.fromHttpUrl(recommendationsServiceHostname)
.path("/recommendations/related")
.query(request.getQueryString()).build();
if (shouldRouteToRecommendationsService(request, uri)) {
logger.info("Calling proxy service");
try {
context.setRouteHost(new URL(uri.toString()));
} catch (MalformedURLException ex) {
logger.error("MalformedURLException for URL:" + uri.toString());
}
}
else
{
//Something here or Solution that should handle a request like a filter is not present.
}
return null;
}
Its working fine for if part and sending the request to proxy service. Problem is for else part.
What I am looking for is in else scenario it should behave like filter never existed and it should handle request it was handling early executing API call from local code.
Any hack or proper solution for this one ?

Customizing the criteria for triggering Fallback in Hystrix Circuit Breaker

I would like to trigger a fallback from a #HystrixCommand Method based on my own criteria (checking for a specific response status).
My method basically acts as a client which calls a service in another URL (marked here as URL).
Here is my code:
#HystrixCommand(fallbackMethod="fallbackPerformOperation")
public Future<Object> performOperation(String requestString) throws InterruptedException {
return new AsyncResult<Object>() {
#Override
public Object invoke() {
Client client = null;
WebResource webResource = null;
ClientResponse response =null;
String results = null;
try{
client = Client.create();
webResource = client.resource(URL);
client.setConnectTimeout(10000);
client.setReadTimeout(10000);
response = webResource.type("application/xml")
.post(ClientResponse.class, requestString);
logger.info("RESPONSE STATUS: " + response.getStatus());
if (response.getStatus() != 200) {
webResource = null;
logger.error(" request failed with the HTTP Status: " + response.getStatus());
throw new RuntimeException(" request failed with the HTTP Status: "
+ response.getStatus());
}
results = response.getEntity(String.class);
} finally {
client.destroy();
webResource = null;
}
return results;
}
};
}
This triggers the fallback Method fallbackPerformOperation() when the response status code is not 200 i.e. response.getStatus()!=200.
The fallback method returns a string which tells the user that the Request did not return a status of 200 and so it is falling back.
I want to know if I can trigger the fallback without having to explicitly throw an exception inside my performOperation() Method.
Could I use #HystrixProperty? I know people mostly use it for timeouts and volume thresholds but could I write a custom #HystrixProperty that checks if the response status is 200 or not within my Method?

Resources