How to get response code from synchronous RequestFuture request

1k views Asked by At

I am using the strava API for an app. I am making synchronous requests as can be seen by the code below.

 try {
            RequestQueue queue = Volley.newRequestQueue(context);
            RequestFuture<String> future = RequestFuture.newFuture();
            StringRequest request = new StringRequest(Request.Method.GET, urlRequest, future, future);
            queue.add(request);

            dataResponse = dealWithResponse(future.get()); 

        } catch (ExecutionException e) {
            System.err.println(e.getLocalizedMessage());
            System.err.println(e.getMessage());
            System.err.println(e.toString());
        } catch (java.lang.Exception e) {
            e.printStackTrace();
        }

I want to know how can I get the response code in the event of an error? for example some rides I request have been deleted / are private and i receive a 404 error code. Other times I have run out of API requests and get a code of 403. How can i differentiate between the thrown errors.

Thank you very much for your help!

2

There are 2 answers

4
Sdghasemi On BEST ANSWER

Override parseNetworkError on your request:

StringRequest request = new StringRequest(Request.Method.GET, urlRequest, future, future) {
    @Override
    protected VolleyError parseNetworkError(VolleyError volleyError) {
        if (volleyError != null && volloeyError.networkResponse != null) {
            int statusCode = volleyError.networkResponse.statusCode;
            switch (statusCode) {
                case 403:
                    // Forbidden
                    break;
                case 404:
                    // Page not found
                    break;
            }
        }
        return volleyError;
    }
};
0
Guy Chen On

In your catch clause, where you handle the ExecutionException you can add the following:

if (e.getCause() instanceof ClientError) {
    ClientError error = (ClientError)e.getCause();
    switch (error.networkResponse.statusCode) {
        //Handle error code
    }
}