Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Map XXX error status codes during failed responses #1053

Merged
merged 2 commits into from
Feb 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Changed

- Map `XXX` error status code range to Parsable Exception object if more specific error status code range is not found.
baywet marked this conversation as resolved.
Show resolved Hide resolved

## [0.12.2] - 2024-02-01

### Changed
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -620,7 +620,8 @@ private Response throwIfFailedResponse(
&& errorMappings.containsKey("4XX"))
&& !(statusCode >= 500
&& statusCode < 600
&& errorMappings.containsKey("5XX"))) {
&& errorMappings.containsKey("5XX"))
&& !errorMappings.containsKey("XXX")) {
spanForAttributes.setAttribute(errorMappingFoundAttributeName, false);
final ApiException result =
new ApiExceptionBuilder()
Expand All @@ -640,8 +641,8 @@ private Response throwIfFailedResponse(
errorMappings.containsKey(statusCodeAsString)
? errorMappings.get(statusCodeAsString)
: (statusCode >= 400 && statusCode < 500
? errorMappings.get("4XX")
: errorMappings.get("5XX"));
? errorMappings.getOrDefault("4XX", errorMappings.get("XXX"))
: errorMappings.getOrDefault("5XX", errorMappings.get("XXX")));
boolean closeResponse = true;
try {
final ParseNode rootNode = getRootParseNode(response, span, span);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,10 @@

import okio.Okio;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.stubbing.Answer;

Expand All @@ -39,15 +40,18 @@
import java.io.InputStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

public class OkHttpRequestAdapterTest {
@ParameterizedTest
@EnumSource(
value = HttpMethod.class,
names = {"PUT", "POST", "PATCH"})
public void PostRequestsShouldHaveEmptyBody(HttpMethod method)
void postRequestsShouldHaveEmptyBody(HttpMethod method)
throws Exception { // Unexpected exception thrown: java.lang.IllegalArgumentException:
// method POST must have a request body.
final AuthenticationProvider authenticationProviderMock =
Expand All @@ -70,7 +74,7 @@ public Request test() throws Exception {

@ParameterizedTest
@ValueSource(ints = {200, 201, 202, 203, 206})
void SendStreamReturnsUsableStream(int statusCode) throws Exception {
void sendStreamReturnsUsableStream(int statusCode) throws Exception {
final var authenticationProviderMock = mock(AuthenticationProvider.class);
authenticationProviderMock.authenticateRequest(
any(RequestInformation.class), any(Map.class));
Expand Down Expand Up @@ -113,7 +117,7 @@ void SendStreamReturnsUsableStream(int statusCode) throws Exception {

@ParameterizedTest
@ValueSource(ints = {200, 201, 202, 203, 204})
public void SendStreamReturnsNullOnNoContent(int statusCode) throws Exception {
void sendStreamReturnsNullOnNoContent(int statusCode) throws Exception {
final var authenticationProviderMock = mock(AuthenticationProvider.class);
authenticationProviderMock.authenticateRequest(
any(RequestInformation.class), any(Map.class));
Expand Down Expand Up @@ -142,7 +146,7 @@ public void SendStreamReturnsNullOnNoContent(int statusCode) throws Exception {

@ParameterizedTest
@ValueSource(ints = {200, 201, 202, 203, 204, 205})
public void SendReturnsNullOnNoContent(int statusCode) throws Exception {
void sendReturnsNullOnNoContent(int statusCode) throws Exception {
final var authenticationProviderMock = mock(AuthenticationProvider.class);
authenticationProviderMock.authenticateRequest(
any(RequestInformation.class), any(Map.class));
Expand Down Expand Up @@ -172,7 +176,7 @@ public void SendReturnsNullOnNoContent(int statusCode) throws Exception {

@ParameterizedTest
@ValueSource(ints = {200, 201, 202, 203})
public void SendReturnsObjectOnContent(int statusCode) throws Exception {
void sendReturnsObjectOnContent(int statusCode) throws Exception {
final var authenticationProviderMock = mock(AuthenticationProvider.class);
authenticationProviderMock.authenticateRequest(
any(RequestInformation.class), any(Map.class));
Expand Down Expand Up @@ -209,15 +213,38 @@ public void SendReturnsObjectOnContent(int statusCode) throws Exception {
assertNotNull(response);
}

@Test
public void throwsAPIException() throws Exception {
private static Stream<Arguments> providesErrorMappings() {
return Stream.of(
// unexpected error code exception
Arguments.of(404, null, false),
Arguments.of(400, Arrays.asList("5XX"), false),
Arguments.of(503, null, false),
Arguments.of(502, Arrays.asList("4XX"), false),
Arguments.of(502, Arrays.asList(""), false),
// expect deserialized exception
Arguments.of(404, Arrays.asList("404"), true),
Arguments.of(500, Arrays.asList("500"), true),
Arguments.of(404, Arrays.asList("XXX"), true),
Arguments.of(500, Arrays.asList("XXX"), true),
Arguments.of(404, Arrays.asList("5XX", "XXX"), true),
Arguments.of(500, Arrays.asList("4XX", "XXX"), true));
}

@SuppressWarnings("unchecked")
@ParameterizedTest
@MethodSource("providesErrorMappings")
void throwsAPIException(
int responseStatusCode,
List<String> errorMappingCodes,
boolean expectDeserializedException)
throws Exception {
final var authenticationProviderMock = mock(AuthenticationProvider.class);
authenticationProviderMock.authenticateRequest(
any(RequestInformation.class), any(Map.class));
final var client =
getMockClient(
new Response.Builder()
.code(404)
.code(responseStatusCode)
.message("Not Found")
.protocol(Protocol.HTTP_1_1)
.request(new Request.Builder().url("http://localhost").build())
Expand All @@ -236,20 +263,33 @@ public void throwsAPIException() throws Exception {
};
final var mockEntity = mock(Parsable.class);
when(mockEntity.getFieldDeserializers()).thenReturn(new HashMap<>());
final var mockParsableFactory = mock(ParsableFactory.class);
when(mockParsableFactory.create(any(ParseNode.class))).thenReturn(mockEntity);
final var mockParseNode = mock(ParseNode.class);
when(mockParseNode.getObjectValue(any(ParsableFactory.class))).thenReturn(mockEntity);
final var mockFactory = mock(ParseNodeFactory.class);
when(mockFactory.getParseNode(any(String.class), any(InputStream.class)))
.thenReturn(mockParseNode);
when(mockFactory.getValidContentType()).thenReturn("application/json");

final var requestAdapter =
new OkHttpRequestAdapter(authenticationProviderMock, mockFactory, null, client);
final var errorMappings =
errorMappingCodes == null
? null
: new HashMap<String, ParsableFactory<? extends Parsable>>();
if (errorMappings != null)
errorMappingCodes.forEach((mapping) -> errorMappings.put(mapping, mockParsableFactory));
final var exception =
assertThrows(
ApiException.class,
() -> requestAdapter.send(requestInformation, null, (node) -> mockEntity));
() ->
requestAdapter.send(
requestInformation, errorMappings, (node) -> mockEntity));
assertNotNull(exception);
assertEquals(404, exception.getResponseStatusCode());
if (expectDeserializedException)
verify(mockParseNode, times(1)).getObjectValue(mockParsableFactory);
assertEquals(responseStatusCode, exception.getResponseStatusCode());
assertTrue(exception.getResponseHeaders().containsKey("request-id"));
}

Expand Down
Loading