Retrofit 2 + Rxjava handling error

前端 未结 2 539
灰色年华
灰色年华 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: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 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

提交回复
热议问题