88import org .commcare .core .network .bitcache .BitCacheFactory ;
99import org .commcare .util .NetworkStatus ;
1010import org .javarosa .core .io .StreamsUtil ;
11+ import org .javarosa .core .services .Logger ;
1112
1213import java .io .IOException ;
1314import java .io .InputStream ;
1415import java .io .OutputStream ;
16+ import java .nio .charset .StandardCharsets ;
1517import java .util .HashMap ;
1618import java .util .List ;
1719import java .util .Map ;
@@ -99,6 +101,12 @@ public InputStream getResponseStream() throws IOException {
99101 return requester .getResponseStream (response );
100102 }
101103
104+ @ Nullable
105+ @ Override
106+ public InputStream getErrorResponseStream () throws IOException {
107+ return requester .getErrorResponseStream (response );
108+ }
109+
102110 @ Override
103111 public String getApiVersion () {
104112 return requester .getApiVersion ();
@@ -175,7 +183,15 @@ public static void processResponse(HttpResponseProcessor responseProcessor,
175183 StreamsUtil .closeStream (responseStream );
176184 }
177185 } else if (responseCode >= 400 && responseCode < 500 ) {
178- responseProcessor .processClientError (responseCode );
186+ InputStream errorStream = null ;
187+ try {
188+ errorStream = streamAccessor .getErrorResponseStream ();
189+ responseProcessor .processClientError (responseCode , errorStream );
190+ } catch (Exception e ) {
191+ Logger .exception ("Exception during network error processing" , e );
192+ } finally {
193+ StreamsUtil .closeStream (errorStream );
194+ }
179195 } else if (responseCode >= 500 && responseCode < 600 ) {
180196 responseProcessor .processServerError (responseCode );
181197 } else {
@@ -191,13 +207,26 @@ public static void processResponse(HttpResponseProcessor responseProcessor,
191207
192208 public InputStream getResponseStream (Response <ResponseBody > response ) throws IOException {
193209 InputStream inputStream = response .body ().byteStream ();
210+ return cacheResponse (inputStream , response );
211+ }
212+
213+ private InputStream cacheResponse (InputStream inputStream , Response <ResponseBody > response )
214+ throws IOException {
194215 BitCache cache = BitCacheFactory .getCache (cacheDirSetup , getContentLength (response ));
195216 cache .initializeCache ();
196217 OutputStream cacheOut = cache .getCacheStream ();
197218 StreamsUtil .writeFromInputToOutputNew (inputStream , cacheOut );
198219 return cache .retrieveCache ();
199220 }
200221
222+ @ Nullable
223+ public InputStream getErrorResponseStream (Response <ResponseBody > response ) throws IOException {
224+ if (response .errorBody () != null ) {
225+ return cacheResponse ( response .errorBody ().byteStream (), response );
226+ }
227+ return null ;
228+ }
229+
201230 public String getApiVersion () {
202231 return response != null ? response .headers ().get ("x-api-current-version" ) : null ;
203232 }
0 commit comments