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        try {
041            responseJSON = JsonObject.readFrom(responseObj.bodyToString());
042
043            if (responseObj.bodyToString() != null && responseJSON.get("request_id") != null) {
044                requestId = " | " + responseJSON.get("request_id").asString();
045            }
046
047            if (responseObj.bodyToString() != null && responseJSON.get("code") != null) {
048                apiMessage += " " + responseJSON.get("code").asString();
049            }
050
051            if (responseObj.bodyToString() != null && responseJSON.get("message") != null) {
052                apiMessage += " - " + responseJSON.get("message").asString();
053            }
054
055            this.setMessage(message + " [" + responseObj.getResponseCode() + requestId + "]" + apiMessage);
056
057        } catch (Exception ex) {
058            this.setMessage(message + " [" + responseObj.getResponseCode() + "]");
059        }
060    }
061
062    /**
063     * The message to return for the API exception.
064     * @param message the constructed for the API exception.
065     */
066    protected void setMessage(String message) {
067        this.message = message;
068    }
069
070    /**
071     *
072     * @return The constructed message for the API exception.
073     */
074    public String getMessage() {
075        return this.message;
076    }
077}