Using RoboSpice is there a way to get the HTTP Error Code out of an exception?

前端 未结 5 823
失恋的感觉
失恋的感觉 2021-01-31 11:29

I am writing an application that uses RoboSpice. In the request listener onRequestFailure( SpiceException arg0 ) is there a way to know for sure that the error was a result of a

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-31 12:17

    I looked over Spring-Android closer and it seems getRestTemplate().getForObject(...) throws a HttpClientErrorException when a 401 or any network error occurs.

    Looking at the Robo Spice for where they catch that exception I found they catch it in RequestProcessor.java in the processRequest function. They pass the Spring-Android exception in as the throwable inside their SpiceException that inherits from Java exception class.

    So you just do the following inside your RoboSpice RequestListener to see if it a 401 UNAUTHORIZED exception.

        private class MyRequestListener implements RequestListener {
    
        public void onRequestFailure( SpiceException arg0 ) {
    
            if(arg0.getCause() instanceof HttpClientErrorException)
            {
                HttpClientErrorException exception = (HttpClientErrorException)arg0.getCause();
                if(exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED))
                {
                    Ln.d("401 ERROR");
                }
                else
                {
                    Ln.d("Other Network exception");
                }
            }
            else if(arg0 instanceof RequestCancelledException)
            {
                Ln.d("Cancelled");
            }
            else
            {
                Ln.d("Other exception");
            }
        };
    
        public void onRequestSuccess( RESULT result ) {
            Ln.d("Successful request");
        }
    }
    

提交回复
热议问题