Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit response.errorBody() is null

I am doing some REST calls, and getting the response. Some times, the response will not be ok, so I need to parse the response, and present it in a proper way for the user to notice, and react. I have this code:

if(response.code()!=200){
      JSONArray jsonError=null;
      try {
         Log.i("David", "Incorrect response: "+response.errorBody().string());

         jsonError = new JSONArray(response.errorBody().string());//After this line, jsonError is null
         JSONObject message=jsonError.getJSONObject(0);

         String errorJson=message.getString("message");
         Log.i("David", "Error received: "+errorJson);
         AlertDialog.Builder dialog=new AlertDialog.Builder(getActivity());
         dialog.setTitle(getString(R.string.error));
         dialog.setMessage(getString(R.string.errorfound) + errorJson);
         dialog.setPositiveButton(getString(R.string.aceptar), new DialogInterface.OnClickListener() {
             @Override
             public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
              }
                  });
                            dialog.show();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

This way, the logging line "Incorrect response" shows perfectly, with error code, message, etc. This is the JSON received:

[{"coderror":"-2","gravedad":"1","message":"Device imei 34543564768463435345 not logged in","cause":""}]

My problem is, as I said, the logging works ok, but when I try to convert the JSON to a JsonArray...it fails. JsonError object turns out to be null, in the very next line.

Why can't I parse the response? Thank you.

like image 670
Fustigador Avatar asked Nov 11 '15 07:11

Fustigador


1 Answers

As I have commented, you should use String s = response.errorBody().string(); then Log.i("David", "Incorrect response: "+ s; and jsonError = new JSONArray(s);. Don't call response.errorBody().string() twice.

If you try/catch IllegalStateException or Exception you will get info look like the following at logcat

W/System.err: java.lang.IllegalStateException: closed
W/System.err:     at com.squareup.okhttp.internal.http.HttpConnection$FixedLengthSource.read(HttpConnection.java:415)
W/System.err:     at okio.Buffer.writeAll(Buffer.java:956)
W/System.err:     at okio.RealBufferedSource.readByteArray(RealBufferedSource.java:92)
W/System.err:     at com.squareup.okhttp.ResponseBody.bytes(ResponseBody.java:57)
W/System.err:     at com.squareup.okhttp.ResponseBody.string(ResponseBody.java:83)

Hope it helps!

like image 54
BNK Avatar answered Oct 17 '22 01:10

BNK