Getting JSON from RetrofitError object using Retrofit

后端 未结 9 1789
Happy的楠姐
Happy的楠姐 2020-12-24 01:39

I am using the Retrofit library to do REST calls to a service I am using.

If I make an API call to my service and have a failure, the service returns a bit of JSON

9条回答
  •  温柔的废话
    2020-12-24 02:17

    A much neater way to do this is to create a class that can do the parsing/conversion for you, one that you can call anytime, anywhere.

    public class ApiError {
        public String error = "An error occurred";
    
        public ApiError(Throwable error) {
            if (error instanceof HttpException) {
                String errorJsonString = null;
                try {
                    errorJsonString = ((HttpException) 
                    error).response().errorBody().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                JsonElement parsedString = new 
                JsonParser().parse(errorJsonString);
                this.error = parsedString.getAsJsonObject()
                                         .get("error")
                                         .getAsString();
            } else {
                this.error = error.getMessage() != null ? error.getMessage() : this.error;
            }
        }
    }
    

    You can now use this anywhere, like so

    ApiError error = new ApiError(error)
    error.error
    

    This is all from this blog post (which I wrote).

提交回复
热议问题