1 package de.juplo.facebook.client;
3 import de.juplo.facebook.exceptions.GraphApiException;
4 import java.io.ByteArrayInputStream;
5 import java.io.IOException;
6 import java.io.InputStream;
7 import org.springframework.http.HttpHeaders;
8 import org.springframework.http.HttpStatus;
9 import org.springframework.http.client.ClientHttpResponse;
10 import org.springframework.util.FileCopyUtils;
11 import org.springframework.web.client.ResponseErrorHandler;
16 * Error-Handler for error-messages from the Facebook Graph-API.
18 * This error-handler handels responses withe the HTTP-status code
19 * {@code 400 BAD REQUEST}. It tries to extract and parse the error-message
20 * from the HTTP-body. Successfully extracted and parsed messages are mapped
21 * to a hierarchy of exceptions, that reflects the hierarchy of the error-
24 * If the HTTP-status-code of the response is not {@code 400 BAD REQUEST} or
25 * the HTTP-body could not be extracted or parsed, this error-handler
26 * delegates the handling to its parent.
28 * @see <a href="https://developers.facebook.com/docs/graph-api/using-graph-api/v2.5#errors">Graph-API Documentation</a>
29 * @see <a href="http://fbdevwiki.com/wiki/Error_codes">Inofficial Wiki For Facebook-Developers</a>
32 public class GraphApiErrorHandler implements ResponseErrorHandler
34 private final ResponseErrorHandler parent;
37 public GraphApiErrorHandler(ResponseErrorHandler errorHandler)
39 this.parent = errorHandler;
44 public boolean hasError(ClientHttpResponse response) throws IOException
47 HttpStatus.Series.CLIENT_ERROR.equals(response.getStatusCode().series())
48 || this.parent.hasError(response);
52 public void handleError(final ClientHttpResponse response) throws IOException
54 if (!HttpStatus.BAD_REQUEST.equals(response.getStatusCode()))
56 // We will only handle 400 BAD REQUEST
57 parent.handleError(response);
62 if (response.getBody() == null)
64 // There is no body to interpret in the HTTP-message
65 parent.handleError(response);
69 final byte[] body = FileCopyUtils.copyToByteArray(response.getBody());
70 GraphApiException error;
74 error = GraphApiException.create(body);
78 // The body of the HTTP-message could not be parsed.
79 // Let the parent error-handler try to handle the response.
81 // To do so, we have to wrap the original response to fill in
82 // the buffered body, if needed
83 ClientHttpResponse buffered = new ClientHttpResponse()
86 public HttpStatus getStatusCode() throws IOException
88 return response.getStatusCode();
92 public synchronized InputStream getBody() throws IOException
94 return new ByteArrayInputStream(body);
98 public HttpHeaders getHeaders()
100 return response.getHeaders();
104 public String getStatusText() throws IOException
106 return response.getStatusText();
116 public int getRawStatusCode() throws IOException
118 return response.getRawStatusCode();
122 parent.handleError(buffered);