422 响应代码将传递给onFailure方法。

huangapple go评论65阅读模式
英文:

Response code 422 goes to onFailure method

问题

我正在尝试使用 Retrofit 发送注册请求,在创建用户成功时它能够完美运行。然而,当出现错误时,它会从 onResponse 跳转到 onFailure,因此我无法处理从我的服务器抛出的错误。它们都返回一个名为 "message" 的 Json object。我用 Postman 尝试过,它的响应是正确的,但是当我尝试在 Android 中实现时,成功消息可以正常显示,但错误消息则不行。为什么会进入 onFailure?我看到有几个讨论处理 onResponse 方法中错误的主题,但我的问题是,当发生错误时根本没有调用该方法,直接跳转到了 onFailure。

我的 Activity:

RegisterService registerService = BaseServerRetrofit.getRetrofitInstance().create(RegisterService.class);
RegisterCredential registerCredential = new RegisterCredential(username.getText().toString(), email.getText().toString(),
password.getText().toString(), password.getText().toString());

Call<Message> call = registerService.getMessageFromServer(registerCredential);
call.enqueue(new Callback<Message>() {
    @Override
    public void onResponse(Call<Message> call, Response<Message> response) {
        if(response.code() == 422)
            Log.e("400", response.errorBody().toString());
        reg_note.setText(response.body().getMessage());
    }

    @Override
    public void onFailure(Call<Message> call, Throwable t) {
        reg_note.setText("error");
    }
});

RegisterService:

public interface RegisterService {
    String FEED = "/public/api/auth/signup";

    @Headers("Content-Type: application/json")
    @POST(FEED)
    Call<Message> getMessageFromServer(@Body RegisterCredential registerCredential);
}

我不知道是否有必要告诉你们,但成功时,响应代码是 201,而失败时是 422。

编辑 1:

我找到了异常:在第 1 行第 1 列路径 $ 处使用 JsonReader.setLenient(true) 来接受格式不正确的 JSON。

英文:

I'm trying to send a sign up request with retrofit and it works perfectly when creating a user is successful. however, when there's an error, it will jump from onResponse to onFailure, so I can't handle the error thrown from my server. they both return a Json object called "message". I tried with postman and it responded correctly but when I'm trying to do it with android, the successful message is shown without any problem but not the error. why is it going to onFailure? I saw several topics where they handled the error on onResponse method but my problem is that the method is not being called when there's an error at all and moved straight to onFailure.

my Activity:

                    RegisterService registerService = BaseServerRetrofit.getRetrofitInstance().create(RegisterService.class);
                    RegisterCredential registerCredential = new RegisterCredential(username.getText().toString(),email.getText().toString()
                    ,password.getText().toString(),password.getText().toString());

                    Call&lt;Message&gt; call = registerService.getMessageFromServer(registerCredential);
                    call.enqueue(new Callback&lt;Message&gt;() {
                        @Override
                        public void onResponse(Call&lt;Message&gt; call, Response&lt;Message&gt; response) {
                            if(response.code() == 422)
                                Log.e(&quot;400&quot;,response.errorBody().toString());
                            reg_note.setText(response.body().getMessage());
                        }

                        @Override
                        public void onFailure(Call&lt;Message&gt; call, Throwable t) {
                            reg_note.setText(&quot;error&quot;);
                        }
                    });

RegisterService

public interface RegisterService {
    String FEED = &quot;/public/api/auth/signup&quot;;

    @Headers(&quot;Content-Type: application/json&quot;)
    @POST(FEED)
    Call&lt;Message&gt; getMessageFromServer(@Body RegisterCredential registerCredential);
}

I don't know if it necessary to tell you guys, but on success, the response code is 201 and when it fails, it is 422.

edit 1:

I found the exception: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $

答案1

得分: 1

好的,这是翻译后的内容:

我查看了可抛出的内容,发现我设置的头部信息不正确,并且返回的不是 JSON 格式的响应。因此,我将头部信息从

@Headers("Content-Type: application/json")

修改为

@Headers("Accept: application/json")
英文:

well, I took a look at the throwable and found out that the header I set was wrong and it was returning a not-Json response. so I changed the header from

@Headers(&quot;Content-Type: application/json&quot;)

to

@Headers(&quot;Accept: application/json&quot;)

答案2

得分: 1

对于那些遇到相同错误却想知道为什么不起作用的人,实际上问题出在您需要检查拦截器,看看是否通过拦截器添加了任何标头,比如令牌。

    Request request = chain.request();
    Request newRequest;

    newRequest = request.newBuilder()
            .addHeader("Authorization", "token")
            .addHeader("Accept", "application/json")
            .build();
英文:

For anyone who are getting same error but wondering this is not working, actually it is you have to check your Interceptor if you are adding any header through there like tokens.

Request request = chain.request();
    Request newRequest;

    newRequest = request.newBuilder()
            .addHeader(&quot;Authorization&quot;, &quot;token&quot;)
            .addHeader(&quot;Accept&quot;, &quot;application/json&quot;)
            .build();

huangapple
  • 本文由 发表于 2020年5月19日 18:10:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/61888453.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定