使用try-catch语句来捕获读取错误,并将其打印输出。
示例代码如下:
Call call = retroInterface.postMethod();
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
if(response.isSuccessful()){
//Do something with the response
}
else{
try {
String errorBody = response.errorBody().string();
Log.d("Error", errorBody);
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void onFailure(Call call, Throwable t) {
Log.d("Failure", t.getMessage());
}
});
此方法解决了在使用Retrofit时无法成功读取ErrorBody.String()的问题,使用try-catch语句可以捕获错误并帮助我们找到问题所在。