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/** 009 * Thrown to indicate than an error occured while returning with a response from the Box API. 010 */ 011public class BoxAPIResponseException extends BoxAPIException { 012 static final long serialVersionUID = -7515717760101647173L; 013 private String message; 014 015 /** 016 * Constructs a BoxAPIException that contains detailed message for underlying exception. 017 * 018 * @param message a message explaining why the error occurred. 019 * @param responseCode a response code. 020 * @param bodyString a response body. 021 * @param responseHeaders response headers. 022 */ 023 public BoxAPIResponseException( 024 String message, int responseCode, String bodyString, Map<String, List<String>> responseHeaders 025 ) { 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 + "]" 063 + apiMessage); 064 } else { 065 this.setMessage(message + " [" + responseCode + "]" + apiMessage); 066 } 067 } 068 069 /** 070 * @return The constructed message for the API exception. 071 */ 072 public String getMessage() { 073 return this.message; 074 } 075 076 /** 077 * The message to return for the API exception. 078 * 079 * @param message the constructed for the API exception. 080 */ 081 protected void setMessage(String message) { 082 this.message = message; 083 } 084}