001package com.box.sdk; 002 003import java.util.ArrayList; 004import java.util.List; 005import java.util.Map; 006import java.util.TreeMap; 007 008import com.eclipsesource.json.JsonObject; 009 010/** 011 * Thrown to indicate than an error occured while returning with a response from the Box API. 012 */ 013public class BoxAPIResponseException extends BoxAPIException { 014 015 private String message; 016 private BoxAPIResponse responseObj; 017 018 /** 019 * Constructs a BoxAPIException that contains detailed message for underlying exception. 020 * 021 * @param message a message explaining why the error occurred. 022 * @param responseObj a response object from the server. 023 */ 024 public BoxAPIResponseException(String message, BoxAPIResponse responseObj) { 025 super(message, responseObj.getResponseCode(), responseObj.bodyToString()); 026 String requestId = ""; 027 String apiMessage = ""; 028 JsonObject responseJSON = null; 029 this.responseObj = responseObj; 030 031 Map<String, List<String>> responseHeaders = new TreeMap<String, List<String>>(String.CASE_INSENSITIVE_ORDER); 032 for (String headerKey : responseObj.getHeaders().keySet()) { 033 List<String> headerValues = new ArrayList<String>(); 034 headerValues.add(responseObj.getHeaderField(headerKey)); 035 responseHeaders.put(headerKey, headerValues); 036 } 037 038 this.setHeaders(responseHeaders); 039 040 if (this.getHeaders().containsKey("BOX-REQUEST-ID")) { 041 requestId += "." + this.getHeaders().get("BOX-REQUEST-ID").get(0).toString(); 042 } 043 044 try { 045 responseJSON = JsonObject.readFrom(responseObj.bodyToString()); 046 } catch (Exception ex) { 047 // Continue because we will construct the exception message below and return it to user. 048 } 049 050 if (responseJSON != null) { 051 if (responseJSON.get("request_id") != null) { 052 requestId = responseJSON.get("request_id").asString() + requestId; 053 } 054 055 if (responseJSON.get("code") != null) { 056 apiMessage += " " + responseJSON.get("code").asString(); 057 } 058 059 if (responseJSON.get("message") != null) { 060 apiMessage += " - " + responseJSON.get("message").asString(); 061 } 062 } 063 064 if (!requestId.isEmpty()) { 065 this.setMessage(message + " [" + responseObj.getResponseCode() + " | " + requestId + "]" 066 + apiMessage); 067 } else { 068 this.setMessage(message + " [" + responseObj.getResponseCode() + "]" + apiMessage); 069 } 070 } 071 072 /** 073 * The message to return for the API exception. 074 * @param message the constructed for the API exception. 075 */ 076 protected void setMessage(String message) { 077 this.message = message; 078 } 079 080 /** 081 * 082 * @return The constructed message for the API exception. 083 */ 084 public String getMessage() { 085 return this.message; 086 } 087}