The body is printed out readable, if an exception occures during parsing
[facebook-errors] / src / main / java / de / juplo / facebook / errors / GraphApiErrorHandler.java
1 package de.juplo.facebook.errors;
2
3
4 import java.io.ByteArrayInputStream;
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.nio.charset.Charset;
8 import org.slf4j.Logger;
9 import org.slf4j.LoggerFactory;
10 import org.springframework.http.HttpHeaders;
11 import org.springframework.http.HttpStatus;
12 import org.springframework.http.client.ClientHttpResponse;
13 import org.springframework.util.FileCopyUtils;
14 import org.springframework.web.client.ResponseErrorHandler;
15
16
17
18 /**
19  * Error-Handler for error-messages from the Facebook Graph-API.
20  * <p>
21  * This error-handler handels responses withe the HTTP-status code
22  * {@code 400 BAD REQUEST}. It tries to extract and parse the error-message
23  * from the HTTP-body. Successfully extracted and parsed messages are mapped
24  * to a hierarchy of exceptions, that reflects the hierarchy of the error-
25  * codes and -types.
26  * <p>
27  * If the HTTP-status-code of the response is not {@code 400 BAD REQUEST} or
28  * the HTTP-body could not be extracted or parsed, this error-handler
29  * delegates the handling to its parent.
30  *
31  * @see <a href="https://developers.facebook.com/docs/graph-api/using-graph-api/v2.5#errors">Graph-API Documentation</a>
32  * @see <a href="http://fbdevwiki.com/wiki/Error_codes">Inofficial Wiki For Facebook-Developers</a>
33  * @author Kai Moritz
34  */
35 public class GraphApiErrorHandler implements ResponseErrorHandler
36 {
37   private final static Logger LOG =
38       LoggerFactory.getLogger(GraphApiErrorHandler.class);
39
40   private final ResponseErrorHandler parent;
41
42
43   public GraphApiErrorHandler(ResponseErrorHandler errorHandler)
44   {
45     this.parent = errorHandler;
46   }
47
48
49   @Override
50   public boolean hasError(ClientHttpResponse response) throws IOException
51   {
52     return
53         HttpStatus.Series.CLIENT_ERROR.equals(response.getStatusCode().series())
54         || this.parent.hasError(response);
55   }
56
57   @Override
58   public void handleError(final ClientHttpResponse response) throws IOException
59   {
60     GraphApiErrorHandler.handleError(parent, response);
61   }
62
63   public static void handleError(
64       final ResponseErrorHandler parent,
65       final ClientHttpResponse response
66       )
67       throws
68         IOException
69   {
70     if (response.getBody() == null)
71     {
72       // There is no body to interpret in the HTTP-message
73       LOG.warn("Could not convert the response into an exception, because there is no message-body.");
74       parent.handleError(response);
75       return;
76     }
77
78     final byte[] body = FileCopyUtils.copyToByteArray(response.getBody());
79     GraphApiException error;
80
81     try
82     {
83       error = GraphApiException.create(body);
84       if (LOG.isInfoEnabled())
85         LOG.info("error-response: {}", new String(body, Charset.forName("UTF-8")));
86     }
87     catch (Exception e)
88     {
89       // The body of the HTTP-message could not be parsed.
90       // Let the parent error-handler try to handle the response.
91
92       LOG.warn(
93           "Could not convert the response into an exception, " +
94           "because the body is unparsable: error={}, body={}",
95           e.toString(),
96           new String(body, Charset.forName("UTF-8"))
97           );
98
99       // To do so, we have to wrap the original response to fill in
100       // the buffered body, if needed
101       ClientHttpResponse buffered = new ClientHttpResponse()
102       {
103         @Override
104         public HttpStatus getStatusCode() throws IOException
105         {
106           return response.getStatusCode();
107         }
108
109         @Override
110         public synchronized InputStream getBody() throws IOException
111         {
112           return new ByteArrayInputStream(body);
113         }
114
115         @Override
116         public HttpHeaders getHeaders()
117         {
118           return response.getHeaders();
119         }
120
121         @Override
122         public String getStatusText() throws IOException
123         {
124           return response.getStatusText();
125         }
126
127         @Override
128         public void close()
129         {
130           response.close();
131         }
132
133         @Override
134         public int getRawStatusCode() throws IOException
135         {
136           return response.getRawStatusCode();
137         }
138       };
139
140       parent.handleError(buffered);
141       return;
142     }
143
144     throw error;
145   }
146 }