我想在我处理各种错误情况的switch语句中放入错误响应代码。如何从VolleyErros
获取响应代码。
错误:
E / Volley:[205] BasicNetwork.performRequest:https://api.abc.com:3211/newuser的意外响应代码409
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if(error != null && error.getMessage() != null)
{
Log.e("Response error", error.getMessage());
}
switch (error.toString()){
case "409" : errorBox.setText("username already exists");
break;
case "410" : errorBox.setText("email already exists");
break;
case "411" : errorBox.setText("xyz already exists");
break;
case "413" : errorBox.setText("abc already exists");
break;
case "414" : errorBox.setText("username invalid ");
break;
default :
Log.d(TAG, "onErrorResponse: "+error.toString());
break;
}
}
}
P.S。: Switch应仅处理 < 409 >响应代码。
答案 0 :(得分:2)
使用statusCode
这是一个int。 docs
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if(error != null && error.getMessage() != null)
{
Log.e("Response error", error.getMessage());
}
switch (error.networkResponse.statusCode){
case 409 : errorBox.setText("username already exists");
break;
case 410 : errorBox.setText("email already exists");
break;
case 411 : errorBox.setText("xyz already exists");
break;
case 413 : errorBox.setText("abc already exists");
break;
case 414 : errorBox.setText("username invalid ");
break;
default :
Log.d(TAG, "onErrorResponse: "+error.toString());
break;
}
}
}
您还应该进行无效检查以验证' networkResponse'不是空的。
if(error.networkResponse!= null){
// switch code
}