Skip to content

Commit

Permalink
BAH-3419 | Handle exceptions based on response. (#98)
Browse files Browse the repository at this point in the history
* Deepti,Parvathy|BAH-3419|Add. Response checker to handle exception.

* Deepti,Parvathy|BAH-3419|Add. Handle other exceptions in Response Checker.

* Deepti,Sweety|BAH-3419|Add. OdooRestException class

* BAH-3419|Deepti|Add. Test case for Response Checker.

* BAH-3419|Deepti|Refactor error message.

* BAH-3419|Deepti|Changed from log4j to slf4j

* BAH-3419|Modified OdooRestException message.

---------

Co-authored-by: parvathy00 <[email protected]>
  • Loading branch information
deeptirawat1510 and parvathy00 authored Jan 3, 2024
1 parent dc11394 commit 9891bdb
Show file tree
Hide file tree
Showing 4 changed files with 144 additions and 6 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package org.bahmni.openerp.web;

public class OdooRestException extends RuntimeException{
public OdooRestException(String message, Throwable cause) {
super(message, cause);
}

public OdooRestException(Throwable cause) {
super(cause);
}

public OdooRestException(String message) {
super(message);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package org.bahmni.openerp.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.ResponseEntity;

public class ResponseChecker {
public static void checkResponse(ResponseEntity<String> responseEntity) throws JsonProcessingException {
String response = responseEntity.getBody();
if (!responseEntity.getStatusCode().is2xxSuccessful()) {
throw new OdooRestException(String.format("Response status: %s", responseEntity.getStatusCode()));
}
if (response == null) {
throw new OdooRestException(String.format("Response is null"));
}
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonResponse = objectMapper.readTree(response);
if (jsonResponse.has("result")) {
JsonNode result = jsonResponse.get("result");
if (result.has("error")) {
String errorMsg = result.get("error").asText();
int status = result.get("status").asInt();
throw new OdooRestException(String.format("Error found in result. Response status: %s. Error message: %s", status, errorMsg));
}
}
else if (jsonResponse.has("error")) {
JsonNode error = jsonResponse.get("error");
String errorMsg = error.get("message").asText();
int status = error.get("status").asInt();
throw new OdooRestException(String.format("Error found in response. Response status: %s. Error message: %s", status, errorMsg));
}
else{
throw new OdooRestException(String.format("Response is empty"));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,13 @@
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.bahmni.openerp.web.OdooRestException;

import org.bahmni.openerp.web.OpenERPException;
import org.bahmni.openerp.web.ResponseChecker;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.reactive.function.client.WebClient;

import java.time.Duration;
Expand Down Expand Up @@ -64,21 +68,22 @@ public String post(String URL, String requestBody) {
WebClient client = getWebClient(baseURL);
HttpHeaders headers = getHttpHeaders();
Consumer < HttpHeaders > consumer = httpHeaders -> httpHeaders.addAll(headers);
String response = client.post().uri(URL).headers(consumer).cookie("session_id", sessionId).bodyValue(requestBody).retrieve().bodyToMono(String.class).timeout(Duration.ofMillis(connectionTimeout)).block();
ResponseEntity<String> responseEntity = client.post().uri(URL).headers(consumer).cookie("session_id", sessionId).bodyValue(requestBody).retrieve().toEntity(String.class).timeout(Duration.ofMillis(connectionTimeout)).block();
ResponseChecker.checkResponse(responseEntity);
String response = responseEntity.getBody();
logger.debug("\n-----------------------------------------------------{} Initiated-----------------------------------------------------\n* Cookies : {}\n* Request : {}\n* Response : {}\n-----------------------------------------------------End of {}-----------------------------------------------------", URL, sessionId, requestBody, response, URL);
if (response == null) {
throw new OpenERPException(String.format("Could not post to %s", URL));
}
logger.debug("Post Data output: {}", response);
logger.debug("Post Data output: {}", response);
return response;
} catch (OdooRestException e) {
logger.error("Post call to {} failed", URL, e);
logger.error("Post data: {}", requestBody);
throw new RuntimeException("Post call to " + URL + " failed", e);
} catch (Exception e) {
logger.error("Could not post to {}", URL, e);
logger.error("Post data: {}", requestBody);
throw new RuntimeException("Could not post message", e);
}
}

private WebClient getWebClient(String baseURL) {
if (webClient == null) {
webClient = WebClient.builder()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package org.bahmni.openerp.web;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class ResponseCheckerTest {

private ResponseChecker responseChecker;

@Before
public void setUp() {
responseChecker = new ResponseChecker();
}

@Test
public void shouldThrowOdooRestExceptionWhenResponseStatusIsNot2xx() {
ResponseEntity<String> mockResponseEntity = mock(ResponseEntity.class);
when(mockResponseEntity.getStatusCode()).thenReturn(HttpStatus.NOT_FOUND);
when(mockResponseEntity.getBody()).thenReturn("Response body");

OdooRestException exception = assertThrows(OdooRestException.class, () -> {
responseChecker.checkResponse(mockResponseEntity);
});
assertEquals("Response status: 404 NOT_FOUND", exception.getMessage());
}

@Test
public void shouldThrowOdooRestExceptionWhenResponseIsNull() {
ResponseEntity<String> mockResponseEntity = mock(ResponseEntity.class);
when(mockResponseEntity.getStatusCode()).thenReturn(HttpStatus.OK);
when(mockResponseEntity.getBody()).thenReturn(null);

OdooRestException exception = assertThrows(OdooRestException.class, () -> {
responseChecker.checkResponse(mockResponseEntity);
});
assertEquals("Response is null", exception.getMessage());
}

@Test
public void shouldThrowOdooRestExceptionWhenResponseHasErrorInResult() {
ResponseEntity<String> mockResponseEntity = mock(ResponseEntity.class);
when(mockResponseEntity.getStatusCode()).thenReturn(HttpStatus.OK);
when(mockResponseEntity.getBody()).thenReturn("{\"result\":{\"error\":\"Error message\",\"status\":500}}");

OdooRestException exception = assertThrows(OdooRestException.class, () -> {
responseChecker.checkResponse(mockResponseEntity);
});
assertEquals("Error found in result. Response status: 500. Error message: Error message", exception.getMessage());
}

@Test
public void shouldThrowOdooRestExceptionWhenResponseHasError() {
ResponseEntity<String> mockResponseEntity = mock(ResponseEntity.class);
when(mockResponseEntity.getStatusCode()).thenReturn(HttpStatus.OK);
when(mockResponseEntity.getBody()).thenReturn("{\"error\":{\"message\":\"Error message\",\"status\":500}}");

OdooRestException exception = assertThrows(OdooRestException.class, () -> {
responseChecker.checkResponse(mockResponseEntity);
});
assertEquals("Error found in response. Response status: 500. Error message: Error message", exception.getMessage());
}

@Test
public void shouldThrowOdooRestExceptionWhenResponseIsEmpty() {
ResponseEntity<String> mockResponseEntity = mock(ResponseEntity.class);
when(mockResponseEntity.getStatusCode()).thenReturn(HttpStatus.OK);
when(mockResponseEntity.getBody()).thenReturn("");

OdooRestException exception = assertThrows(OdooRestException.class, () -> {
responseChecker.checkResponse(mockResponseEntity);
});
assertEquals("Response is empty", exception.getMessage());
}
}

0 comments on commit 9891bdb

Please sign in to comment.