Невозможно вернуть код ошибки с сообщением от остальных API при загрузке Spring - PullRequest
0 голосов
/ 14 июня 2019

Я новичок в Spring boot.Я реализовал следующие API остальных в загрузке Spring:

 @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 () в Myservice определяется следующим образом:

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);
  }
}

}

Проблема: во время вызоваЭтот API для недопустимых входных данных, я получаю 500, а не 404 и сообщение об ошибке «Данные не найдены».Может кто-нибудь предложить, пожалуйста, какие изменения я должен внести в приведенный выше код?

РЕДАКТИРОВАТЬ: Как предложено, я добавил следующий класс:

@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);
}

Даже после этого я не могу получить ошибкукод и сообщение об ошибке, как и ожидалось.

Ответы [ 4 ]

1 голос
/ 14 июня 2019

Согласно вашему контроллеру, он генерирует исключение «BusinessException».Но вы не реализовали метод для перехвата этого исключения в советнике контроллера, которое называется «GlobalExceptionHandler».Пожалуйста, включите приведенный ниже метод в ваш контроллер контроллера, поскольку тест прошел успешно.

    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<String> handleBusinessException(BusinessException businessException ) {

        return new ResponseEntity<>("Your specific error", HttpStatus.NOT_FOUND);
    }

Ниже приведен результат теста enter image description here

0 голосов
/ 14 июня 2019

Вместо создания бизнес-исключения вы должны создать комбинированное сообщение, если оба ввода являются недопустимым сообщением об ошибке, а затем вы можете вернуть responseEntity в качестве быстрого исправления:
return new ResponseEntity <> («Неверный ввод»,HttpStatus.NOT_FOUND);

0 голосов
/ 14 июня 2019

Чтобы обработать это исправление через @RestControllerAdvice, вы должны создать пользовательское исключение, которое содержит код httpStatus и сообщение, которое вы хотите вернуть

public class CustomBusinessException extends Exception{

/**
 * 
 */
private static final long serialVersionUID = 1L;

private final String status;
private final String requestMessage;
private final String description;


    public CustomBusinessException (Throwable ex,String status, String requestMessage, String description) {
    super(ex);
    this.status = status;
    this.requestMessage = requestMessage;
    this.description = description;
}
//create getter and setter

}

обработайте это исключение через пользовательский обработчик исключений (@RestCOntrollerAdvice) и подготовьте настраиваемый ответ для отправки следующим образом

@ExceptionHandler({ CustomBusinessException .class })
public ResponseEntity<CustomBusinessResponse> handleAll(CustomBusinessException customBusinessException , WebRequest request) {

    logger.error("Exception occured in NRACustomExceptionHandler :"+ExceptionUtils.getStackTrace(nraGatewayException));
    CustomBusinessResponse response = new CustomBusinessResponse();
    response.setMessage(customBusinessException.getRequestMessage());
    response.setDescription(customBusinessException.getDescription());

    return new ResponseEntity<>(response, new HttpHeaders(), HttpStatus.valueOf(Integer.parseInt(customBusinessException.getStatus())));
}

Создание пользовательского класса ответа

public class NRAExceptionResponse {

private String message;

private String description;


//create getter and setter
}

выбрасывает пользовательское исключение со статусом для отправки следующим образом

  throw new NRAGatewayException(e, "404","Invalid Input", "Invalid input 1 and input 2");
0 голосов
...