Centralized error handling retrofit 2?

前端 未结 4 1617
小蘑菇
小蘑菇 2020-12-31 03:14

Before retrofit 2, there was a way of handling erros centrally -

new retrofit.RestAdapter.Builder()
        .setEndpoint(apiUrl)
        .setLogLevel(retro         


        
4条回答
  •  星月不相逢
    2020-12-31 03:48

    I have used similar solution as Amir proposes but I'm just wondering if this could be made even easier. I tried the following:

    public void onResponse(Response response) {
            if (response.isSuccess()) {
                T resp = response.body();
                handleSuccessResponse(resp);
    
            } else {
                Response statusResponse = response.error(response.code(), response.errorBody());
                handleHttpErrorResponse(statusResponse);
            }
        }
    

    This way I would not need to pass Retrofit instance around. However I'm missing something as error body is not successfully parsed to StatusResponse. I'm not sure what this means in practice:

    The change in 2.0.0-beta2 which provided the Retrofit instance to the onResponse callback of Callback has been reverted. There are too many edge cases around providing the Retrofit object in order to allow deserialization of the error body. To accommodate this use case, pass around the Retrofit response manually or implement a custom CallAdapter.Factory does so automatically.

    2.0.0-beta3

提交回复
热议问题