I am new to Spring boot. I have implemented following rest api in Spring boot:
@GetMapping(value = "/output")
public ResponseEntity<?> getListOfPOWithItem(@QueryParam("input1") String input1,
@QueryParam("input2") String input2)
throws BusinessException {
if (input1 == null) {
throw new BusinessException("Query param input1 is null or invalid");
}
if (input2 == null) {
throw new BusinessException("Query param input2 is null or invalid");
}
List<Output> outputList =
myService.getDetails(input1, input2);
if (outputList != null) {
return new ResponseEntity<List<Ouput>>(outputList, HttpStatus.OK);
}
return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
}
getDetails() in Myservice is defined as below:
public List<Output> getDetails(String input1, String input2)
throws BusinessException {
String path = new StringBuilder().append(getBaseUrl()).append("/input1/")
.append(input1).append("/input2/").append(input2).toString();
try {
ResponseEntity<List<Output>> responseEntityList = restTemplate.exchange(path,
HttpMethod.GET, null, new ParameterizedTypeReference<List<Output>>() {});
List<Output> outputList = responseEntity.getBody();
if (responseEntityList.isEmpty()) {
throw new EntityNotFoundException("Input not found",
ExternalServicesErrorCode.NO_DATA_FOUND);
}
return outputList;
} catch (HttpStatusCodeException e) {
int statusCode = e.getStatusCode().value();
if (statusCode == Status.NOT_FOUND.getStatusCode()) {
throw new EntityNotFoundException("Data not found",
ExternalServicesErrorCode.NO_DATA_FOUND);
} else {
throw new BusinessException("Error in getting data", ExternalServicesErrorCode.SERVICE_ERROR);
}
}
}
Problem is: while invoking this API for invalid inputs, I am getting 500, not 404 and error message "No data found". Can anyone please suggest what change should I make in the above code ?
EDIT: As suggested, I have added following class:
@RestControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(Exception.class)
public final ResponseEntity<ExceptionResponse>
handleAllExceptions(Exception ex,
WebRequest request) {
ExceptionResponse exceptionResponse = new ExceptionResponse(Instant.now().toEpochMilli(),
ex.getMessage(), request.getDescription(true));
return new ResponseEntity<>(exceptionResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(EntityNotFoundException.class)
public final ResponseEntity<ExceptionResponse> handleEntityNotFoundException(
EntityNotFoundException ex, WebRequest request) {
ExceptionResponse exceptionResponse = new ExceptionResponse(Instant.now().toEpochMilli(),
ex.getMessage(), request.getDescription(true));
return new ResponseEntity<>(exceptionResponse, HttpStatus.NO_CONTENT);
}
Even after that I am unable to get the error code and error message as expected.