Added JSON-mapping for responses from the Graph-API
[facebook-errors] / src / main / java / de / juplo / facebook / exceptions / GraphApiException.java
1 package de.juplo.facebook.exceptions;
2
3 import com.fasterxml.jackson.annotation.JsonProperty;
4 import com.fasterxml.jackson.annotation.JsonPropertyOrder;
5 import com.fasterxml.jackson.annotation.JsonRootName;
6 import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
7
8 /**
9  * Base exception for Facebook Graph-Api exceptions.
10  * 
11  * @author Kai Moritz
12  */
13 @org.codehaus.jackson.map.annotate.JsonDeserialize(using = GraphApiExceptionJackson1Deserializer.class)
14 @com.fasterxml.jackson.databind.annotation.JsonDeserialize(using = GraphApiExceptionJackson2Deserializer.class)
15 public class GraphApiException extends OAuth2Exception
16 {
17   private final String type;
18   private final int code;
19
20   private int httpErrorCode;
21
22
23   public GraphApiException(String message, String type, int code)
24   {
25     super(message);
26     this.type = type;
27     this.code = code;
28   }
29
30
31   public String getType()
32   {
33     return type;
34   }
35
36   public int getCode()
37   {
38     return code;
39   }
40
41   @Override
42   public int getHttpErrorCode()
43   {
44     return httpErrorCode == 0 ? super.getHttpErrorCode() : httpErrorCode;
45   }
46
47   public void setHttpErrorCode(int httpErrorCode)
48   {
49     this.httpErrorCode = httpErrorCode;
50   }
51
52   @Override
53   public String toString()
54   {
55     StringBuilder builder = new StringBuilder();
56     builder.append("{error:{\"message\":\"");
57     builder.append(getMessage().replaceAll("\"", "\\\""));
58     builder.append("\",\"type\":");
59     builder.append(type.replaceAll("\"", "\\\""));
60     builder.append("\",\"code\":");
61     builder.append(code);
62     builder.append("}}");
63     return builder.toString();
64   }
65
66
67   /**
68    * This class represents an error message from the Graph-API
69    *
70    * @see https://developers.facebook.com/docs/graph-api/using-graph-api/v2.5#errors
71    */
72   @JsonRootName("error")
73   @JsonPropertyOrder({ "message", "type", "code", "error_subcode", "error_user_title", "error_user_msg", "fbtrace_id" })
74   public static class FacebookErrorMessage
75   {
76     @JsonProperty("message")
77     String message;
78     @JsonProperty("type")
79     String type;
80     @JsonProperty("code")
81     Integer code;
82     @JsonProperty("error_subcode")
83     Integer subCode;
84     @JsonProperty("error_user_title")
85     String userTitle;
86     @JsonProperty("error_user_msg")
87     String userMessage;
88     @JsonProperty("fbtrace_id")
89     String traceId;
90   }
91 }