2014-09-05 22 views
0

我想知道是否有一個庫將從雲端點拋出的異常映射回客戶端上的Exception對象。拋出在服務器端異常被表示爲GoogleJsonResponseException,包含的真正原因的完整包名:來自GoogleJsonResponseException的雲端點異常映射器

Caused by: com.google.api.client.googleapis.json.GoogleJsonResponseException: 401 Unauthorized 
{ 
    "code": 401, 
    "errors": [ 
    { 
     "domain": "global", 
     "location": "Authorization", 
     "locationType": "header", 
     "message": "com.google.appengine.api.oauth.OAuthRequestException: User not logged in", 
     "reason": "required" 
    } 
    ], 
    "message": "com.google.appengine.api.oauth.OAuthRequestException: User not logged in" 
} 

我想編寫客戶端代碼:

try { 
    // call endpoint 
} catch (OAuthRequestException e) { 
    // handle exception 
} 

我認爲這是可能寫這樣的圖書館。使用代碼處理器和註釋可以生成具有適當例外的客戶端庫。也許客戶端代碼看起來不像下面的代碼,但像這樣:

try { 
    Library.mapExceptions(/* call endpoint */); 
} catch (OAuthRequestException e) { 
    // handle exception 
} 

有沒有什麼可以做這項工作?

回答

1

我不知道這種庫的想法,但你總是可以做:

try { 
    ... 
} catch (IOException) { 
    if (e instanceof GoogleJsonResponseException){ 
     GoogleJsonResponseException ex = e; 
     switch (ex.getStatusCode()){ 
      case 400: 
       ... 
      case 404: 
       ... 
      /*and the rest of codes available through endpoints*/ 
     } 
    } else { 
     /*Manage other exceptions, maybe connection issues?*/ 
    } 
} 
+0

這是我怎麼做。此外,我有一些特定的例外,我還需要解析異常類型。這段代碼很難看,所以我正在尋找一些以美麗的方式處理它的庫。 – tomrozb 2014-09-09 13:13:54