Retrofit 2 + Rxjava handling error

前端 未结 2 520
灰色年华
灰色年华 2020-12-28 18:18

So i already receive a token from the Json when the login is made without problems, and receive the hash

But when the response from the server is a error, i cannot g

相关标签:
2条回答
  • 2020-12-28 18:37

    You are mixing a logical error (login failed for some reason) with an application error. If your server sends response with HTTP 200 and a valid json in case of failed login, your application will not call onError at all.

    So basically you need to check the (successful) response from the server and decide based on the provided json if the login was successful or not.

    onError should be called, for example, in case the server is not reachable or fails to deliver a valid response.

    Edit: I don't know what your TokenResponse contains but basically the response for a login should be the same, no matter if it was successful or not. You then just check the TokenResponse to find out if the result contains errors or not.

    Check this answer as an example: https://stackoverflow.com/a/31159671/180538

    0 讨论(0)
  • 2020-12-28 18:46

    I found a solution, I have a application class that Creates a Retrofit and then i just created a ResponseBody and converted using responseBodyConverter(,)

                    @Override
                    public void onError(Throwable e) {
                        if (e instanceof HttpException) {
                            ResponseBody body = ((HttpException) e).response().errorBody();
    
                            Converter<ResponseBody, Error> errorConverter =
                                application.getRetrofit().responseBodyConverter(Error.class, new Annotation[0]);
                        // Convert the error body into our Error type.
                            try {
                                Error error = errorConverter.convert(body);
                                Log.i("","ERROR: " + error.message);
                                mLoginView.errorText(error.message);
                            } catch (IOException e1) {
                            e1.printStackTrace();
                            }
                         }
    
    
    
                    static class Error{
                    String message;
                    }
    

    the JSon received was {"error":4041,"message":"Email not found"} thas why the class Error, i just created a variable message because i just want need to show the message to the user

    0 讨论(0)
提交回复
热议问题