简体   繁体   English

Retrofit2错误处理

[英]Retrofit2 error handling

I'm using Retrofit2+RxJava. 我正在使用Retrofit2 + RxJava。 When i make request server can return one of two response Succes and Error but in both cases HTTP STATUS CODE = 200. How do achieve that when i get Erron in response body instead calls onNext calls onError? 当我使请求服务器可以返回两个响应成功和错误之一,但在两种情况下,HTTP状态码=200。当我在响应正文中获得Erron而不是调用onNext调用onError时,如何实现?

 Observable<CreateAuth> createAuthObservable = endApiServiceProvider.createAuth(phone);
        Subscription subscription = createAuthObservable
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(createAuth -> {
                          hideProgress();
                          successAuth(phone);

                        },
                        throwable -> {
                            //todo correct handle error
                            hideProgress();
                            if (throwable instanceof IOException) {
                                showError("Network error. Please check your internet connection");
                            }
                        });

My endpoint interface 我的端点界面

@GET("/api/new.php")
Observable<CreateAuth> createAuth(@Query("username") String uname);

Succes Response (HTTP code 200) and CreateAuth.java POJO structure as below 成功响应(HTTP代码200)和CreateAuth.java POJO结构如下

{
 "val": true,
 "message": "Success!"
}

Error Response (HTTP code 200) and ErrorResponse.java POJO structure as below 错误响应(HTTP代码200)和ErrorResponse.java POJO结构如下

{
    "error_type": "wrong_c",
    "error_additional": "Illegal char in name!"
}

I'd say this is a server-side issue rather than a problem with your client-side code. 我想说这是服务器端的问题,而不是客户端代码的问题。 You receive HTTP 200 for both success and error responses, then this would not automatically throw an error in Retrofit. 您会收到HTTP 200的成功响应和错误响应,因此不会自动在Retrofit中引发错误。 As far as Retrofit is concerned, the request was a success. 就翻新而言,该请求是成功的。

You'd need to analyse what was returned and handle it appropriately if you want to keep your server configuration the same, therefore both success and error responses must me parsable into the same class. 如果要保持服务器配置相同,则需要分析返回的内容并进行适当的处​​理,因此成功和错误响应都必须解析为同一类。

Alternatively, re-configure your endpoints to return a 4xx response on error. 或者,重新配置端点以返回4xx错误响应。 I'd recommend this approach. 我建议这种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM