throwException(Response)   A
last analyzed

Complexity

Conditions 3

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 13
rs 9.4285
cc 3
1
package com.base.Http.Response.Handlers;
2
3
import com.base.Exceptions.BaseHttpException;
4
import com.base.Exceptions.Http.InputError;
5
import com.base.Exceptions.Http.NotFound;
6
import com.base.Http.Response.ErrorBag;
7
import com.base.Http.Response.Response;
8
import com.google.gson.Gson;
9
import com.google.gson.GsonBuilder;
10
11
public class BaseResponseHandler implements HandlerInterface {
12
13
    /**
14
     * It will take Response as argument.
15
     * It will throw {@link NotFound} Exception when Response's StatusCode is equals-to 404
16
     * and throw {@link BaseResponseHandler.inputError} Exception if StatusCode is equals-to 422
17
     * else it will throw {@link BaseHttpException}
18
     *
19
     * @param response
20
     * @throws BaseHttpException
21
     */
22
    private static void throwException(Response response) throws BaseHttpException {
23
        int statusCode = response.getStatusCode();
24
        String message = response.getBody();
25
26
        if (statusCode == 404) {
27
            throw new NotFound(statusCode, message, response);
28
        }
29
30
        if (statusCode == 422) {
31
            throw BaseResponseHandler.inputError(statusCode, message, response);
32
        }
33
34
        throw new BaseHttpException(statusCode, message, response);
35
    }
36
37
    /**
38
     * Throw An Exception according to status code
39
     *
40
     * @param statusCode Request's status code
41
     * @param message    Request's Message
42
     * @param response   Response
43
     * @return BaseHttpException exception
44
     */
45
    private static BaseHttpException inputError(int statusCode, String message, Response response) {
46
        InputError error = new InputError(statusCode, message, response);
47
        GsonBuilder builder = new GsonBuilder();
48
        Gson gson = builder.create();
49
50
        ErrorBag errorBag = gson.fromJson(response.getBody(), ErrorBag.class);
51
        error.setErrorBag(errorBag);
52
53
        return error;
54
    }
55
56
    /**
57
     * It will throw an exception when Response's StatusCode is grater than or equal to 400.
58
     *
59
     * @param response {@link Response}
60
     * @return Response
61
     * @throws BaseHttpException Exception
62
     */
63
    public Response handle(Response response) throws BaseHttpException {
64
        int code = response.getStatusCode();
65
66
        if (code >= 400) {
67
            BaseResponseHandler.throwException(response);
68
        }
69
70
        return response;
71
    }
72
73
}
74