【问题标题】:How can I throw a custom exception from Volley's onResponse and onErrorResponse methods如何从 Volley 的 onResponse 和 onErrorResponse 方法中抛出自定义异常
【发布时间】:2020-01-10 21:13:08
【问题描述】:

我有访问 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);}

【问题讨论】:

    标签: android exception android-volley


    【解决方案1】:

    我想我可能有一个解决方案,但由于不了解 Volley 的请求如何运作,我不能 100% 确定。如果请求是同步的,这是否是解决问题的一种方式?通过添加一个已分配的 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);}
    

    【讨论】:

      猜你喜欢
      • 2016-06-04
      • 2018-08-08
      • 2011-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-30
      • 1970-01-01
      相关资源
      最近更新 更多