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