package util;

import exception.BadRequestException;
import exception.FilestackIOException;
import exception.HandleNotFoundException;
import exception.PolicySignatureException;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;

/**
 * Checks for failed responses from Filestack and throws an exception rather than returning the response.
 * Makes error handling simpler by centralizing this logic in one place.
 */
public class FailedResponseInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);

        // If it was successful we don't need to do anything else
        if (response.isSuccessful())
            return response;

        // We're only concerned with responses from Filestack domains
        if (!request.url().host().contains("filestack"))
            return response;

        // Throw a descriptive subclass of FilestackIOException
        switch (response.code()) {
            case 400:
                throw new BadRequestException();
            case 403:
                throw new PolicySignatureException();
            case 404:
                throw new HandleNotFoundException();
            default:
                String message = String.format("Request failed: %d %s", response.code(), response.message());
                throw new FilestackIOException(message);
        }
    }
}

@@ -29,142 +29,19 @@
 ion.
-BadRequestException;%0Aimport exception.FilestackIOException;%0Aimport exception.HandleNotFoundException;%0Aimport exception.PolicySignature
+FilestackIO
 Exce
@@ -123,16 +123,45 @@
 esponse;
+%0Aimport okhttp3.ResponseBody;
 %0A%0Aimport
@@ -607,16 +607,61 @@
 equest);
+%0A        ResponseBody body = response.body();
 %0A%0A      
@@ -799,570 +799,169 @@
     
-// We're only concerned with responses from Filestack domains%0A        if (!request.url().host().contains(%22filestack%22))%0A            return response;%0A%0A        // Throw a descriptive subclass of FilestackIOException%0A        switch (response.code()) %7B%0A            case 400:%0A                throw new BadRequestException();%0A            case 403:%0A                throw new PolicySignatureException();%0A            case 404:%0A                throw new HandleNotFoundException();%0A            default:%0A                String message = String.format(%22Request failed: %25d %25s%22,
+if (body != null)%0A            throw new FilestackIOException(body.string());%0A        else%0A            throw new FilestackIOException(request.url().host() + %22 %22 +
  res
@@ -976,9 +976,16 @@
 de()
-,
+ + %22 %22 +
  res
@@ -1006,75 +1006,8 @@
 ));%0A
-                throw new FilestackIOException(message);%0A        %7D%0A
     

Make failure interceptor generic