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 4xx}. 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 4xx} 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.Series.CLIENT_ERROR.equals(response.getStatusCode().series()))
56 // Let the parent-error-handler handle all errors, that are no client
58 parent.handleError(response);
63 if (response.getBody() == null)
65 // There is no body to interpret in the HTTP-message
66 parent.handleError(response);
70 final byte[] body = FileCopyUtils.copyToByteArray(response.getBody());
71 GraphApiException error;
75 error = GraphApiException.create(body);
79 // The body of the HTTP-message could not be parsed.
80 // Let the parent error-handler try to handle the response.
82 // To do so, we have to wrap the original response to fill in
83 // the buffered body, if needed
84 ClientHttpResponse buffered = new ClientHttpResponse()
87 public HttpStatus getStatusCode() throws IOException
89 return response.getStatusCode();
93 public synchronized InputStream getBody() throws IOException
95 return new ByteArrayInputStream(body);
99 public HttpHeaders getHeaders()
101 return response.getHeaders();
105 public String getStatusText() throws IOException
107 return response.getStatusText();
117 public int getRawStatusCode() throws IOException
119 return response.getRawStatusCode();
123 parent.handleError(buffered);