Retrofit 2 关于HTTP返回码的一点小坑

在Retrofit 1 时,会在onError中返回并抛出HttpException,但是在2中,不会再回调onError了,而是会在onNext中,这个任务就需要客户端自己处理。

https://futurestud.io/tutorials/retrofit-2-simple-error-handling

参考如下:

Error Handler in Action

etrofit 2 has a different concept of handling “successful” requests than Retrofit 1. In Retrofit 2, all requests that can be executed (sent to the API) and for which you’re receiving a response are seen as “successful”. That means, for these requests the onResponse callback is fired and you need to manually check whether the request is actual successful (status 200-299) or erroneous (status 400-599).

If the request finished successfully, we can use the response object and do whatever we wanted. In case the error actually failed (remember, status 400-599), we want to show the user appropriate information about the issue.

As you can see, we use the ErrorUtils class to parse the error body and get an APIError object. Use this object and the contained information to show a meaningful message instead of a generic error message.

 

Leave a Reply

Your email address will not be published.