summaryrefslogtreecommitdiffstats
path: root/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/utils/SDCResponseErrorHandler.java
blob: 64da66a600276fe714d04a7320aa4dc9151affc1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package org.onap.sdc.dcae.utils;

import com.google.gson.Gson;
import org.onap.sdc.dcae.catalog.asdc.ASDCException;
import org.onap.sdc.dcae.errormng.RequestError;
import org.onap.sdc.dcae.errormng.ResponseFormat;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.ResponseErrorHandler;

import java.io.IOException;

public class SDCResponseErrorHandler implements ResponseErrorHandler {

	private ResponseErrorHandler errorHandler = new DefaultResponseErrorHandler();

	private static Gson gson = new Gson();

	public void handleError(ClientHttpResponse response) throws IOException {
		try{
			errorHandler.handleError(response);
		} catch (HttpClientErrorException e) {
			RequestError re = extractRequestError(e);
			throw null == re ? e : new ASDCException(e.getStatusCode(), re);
		}
	}

	public boolean hasError(ClientHttpResponse response) throws IOException{
		return errorHandler.hasError(response);
	}

	private RequestError extractRequestError(HttpClientErrorException error) {
		try {
			String body = error.getResponseBodyAsString();
			ResponseFormat responseFormat = gson.fromJson(body, ResponseFormat.class);
			return responseFormat.getRequestError();
		} catch (Exception e) {
			return null;
		}
	}

}