![](/img/trans.png)
[英]Volley is not calling onResponse or onErrorResponse methods
[英]How can I throw a custom exception from Volley's onResponse and onErrorResponse methods
我有訪問 API 的代碼,該 API 返回一系列用於繪制騎行路線的地理點。 因此,我首先獲取 JSON 對象,然后將其轉換為可繪制點。 對於與此 API 相關的所有異常,我都有一個 APIGenericException,如果對 API 的請求不成功,我想拋出一個 APiRequestException(它是 APIGenericException 的子類)。 我不知道如何拋出這個,因為 Volley 的 onErrorResponse() 方法不會拋出異常。 除此之外,convertResponseToWayPoints 也會拋出異常,但我不確定如何將其傳遞給 onResponse 和 requestRouteFromAPI 方法。
public void requestRouteFromAPI(Context mainActivityContext, final String url) throws APIGenericException {
RequestQueue queue = Volley.newRequestQueue(mainActivityContext);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
convertResponseToWayPoints(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error){
// TODO: Handle error
Log.e("ERROR", "Error occurred ", error);
throw new APiRequestException(url);
}
}); queue.add(jsonObjectRequest);}
我想我可能有一個解決方案,但我不是 100% 確定基於不了解 Volley 的請求是如何運作的。 如果請求是同步的,這是解決問題的一種方式嗎? 通過添加分配的 JSONObject 然后在方法之外處理它。
private JSONObject APIrequestResponse;
public void getRoute(Context mainActivityContext) throws CycleStreetsException {
requestRouteFromCycleStreets(mainActivityContext, getAPIURL());
if(APIrequestResponse == null){
throw new CycleStreetsRequestException(getAPIURL());
}
else{
//make routes
}
}
public void requestRouteFromAPI(Context mainActivityContext, final String url) throws APIGenericException {
RequestQueue queue = Volley.newRequestQueue(mainActivityContext);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
APIrequestResponse = response;
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error){
// TODO: Handle error
Log.e("ERROR", "Error occurred ", error);
APIrequestResponse = null;
}
}); queue.add(jsonObjectRequest);}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.