1010import com .mashape .unirest .http .HttpResponse ;
1111import com .sybit .airtable .vo .Error ;
1212
13+ import java .util .Map ;
14+
1315/**
1416 * Handle HTTP responses and create exceptions.
1517 *
@@ -22,36 +24,27 @@ public static void onResponse(HttpResponse response) throws AirtableException {
2224 final Integer statusCode = response .getStatus ();
2325 String message = convertStreamToString (response .getRawBody ());
2426
25- final Gson gson = new Gson ();
26- Error err = gson .fromJson (message , Error .class );
27- switch (statusCode ) {
28- case 401 :
29- throw new AirtableException ("AUTHENTICATION_REQUIRED" , "You should provide valid api key to perform this operation" , statusCode );
30- case 403 :
31- throw new AirtableException ("NOT_AUTHORIZED" , "You are not authorized to perform this operation" , statusCode );
32-
33- case 404 :
34- message = ( err .getMessage () != null ) ? err .getMessage () : "Could not find what you are looking for" ;
35- throw new AirtableException ("NOT_FOUND" , message , statusCode );
36-
37- case 413 :
38- throw new AirtableException ("REQUEST_TOO_LARGE" , "Request body is too large" , statusCode );
27+ Error err = extractError (message );
3928
40- case 422 :
41- throw new AirtableException (err .getType (), err .getMessage (), statusCode );
42-
43- case 429 :
44- throw new AirtableException ("TOO_MANY_REQUESTS" , "You have made too many requests in a short period of time. Please retry your request later" , statusCode );
29+ throw new AirtableException (err .getType (), err .getMessage (), statusCode );
30+ }
4531
46- case 500 :
47- throw new AirtableException ("SERVER_ERROR" , "Try again. If the problem persists, contact support." , statusCode );
32+ private static Error extractError (String message ) {
4833
49- case 503 :
50- throw new AirtableException ("SERVICE_UNAVAILABLE" , "The service is temporarily unavailable. Please retry shortly." , statusCode );
34+ final Gson gson = new Gson ();
5135
52- default :
53- throw new AirtableException ("UNDEFINED_ERROR" , message , statusCode );
36+ Error err ;
37+ try {
38+ Map <String , Object > jsonMap = gson .fromJson (message , Map .class );
39+ String innerJson = gson .toJson (jsonMap .get ("error" ));
40+ err = gson .fromJson (innerJson , Error .class );
41+ } catch (Exception ignored ) {
42+ err = new Error ();
43+ err .setType ("UNDEFINED_ERROR" );
44+ err .setMessage (message );
5445 }
46+
47+ return err ;
5548 }
5649
5750 public static String convertStreamToString (java .io .InputStream is ) {
0 commit comments