Skip to content

Commit

Permalink
feat(retrofit): add accessor to exception response body as a map
Browse files Browse the repository at this point in the history
  • Loading branch information
SheetalAtre committed Jul 7, 2023
1 parent 18d1c6e commit 20d2bef
Showing 1 changed file with 15 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Preconditions;
import com.netflix.spinnaker.kork.annotations.NonnullByDefault;
import java.util.Optional;
import java.util.HashMap;
import java.util.Map;
import lombok.Getter;
import org.springframework.http.HttpHeaders;
import retrofit.RetrofitError;
Expand Down Expand Up @@ -50,20 +51,19 @@ public SpinnakerHttpException(RetrofitError e) {
super(e);
this.response = e.getResponse();
this.retrofit2Response = null;
RetrofitErrorResponseBody body =
(RetrofitErrorResponseBody) e.getBodyAs(RetrofitErrorResponseBody.class);
Map<String, Object> body = getResponseBody(e);

this.rawMessage =
Optional.ofNullable(body).map(RetrofitErrorResponseBody::getMessage).orElse(e.getMessage());
body != null ? (String) body.getOrDefault("message", e.getMessage()) : e.getMessage();
}

public SpinnakerHttpException(RetrofitException e) {
super(e);
this.response = null;
this.retrofit2Response = e.getResponse();
RetrofitErrorResponseBody body =
(RetrofitErrorResponseBody) e.getErrorBodyAs(RetrofitErrorResponseBody.class);
Map<String, Object> body = getResponseBody(e);
this.rawMessage =
Optional.ofNullable(body).map(RetrofitErrorResponseBody::getMessage).orElse(e.getMessage());
body != null ? (String) body.getOrDefault("message", e.getMessage()) : e.getMessage();
}

private final String getRawMessage() {
Expand Down Expand Up @@ -166,4 +166,12 @@ private static final class RetrofitErrorResponseBody {
this.message = message;
}
}

public Map<String, Object> getResponseBody(RuntimeException e) {
if (this.response != null) {
return (Map<String, Object>) ((RetrofitError) e).getBodyAs(HashMap.class);
} else {
return (Map<String, Object>) ((RetrofitException) e).getErrorBodyAs(HashMap.class);
}
}
}

0 comments on commit 20d2bef

Please sign in to comment.