在Spring Boot中无法从REST API返回错误代码和消息 [英] Not able to return error code with message from rest API in Spring boot

查看:160
本文介绍了在Spring Boot中无法从REST API返回错误代码和消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Spring Boot的新手.我已经在Spring Boot中实现了以下rest api:

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

Myservice中的

getDetails()定义如下:

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

}

问题是:调用此API进行无效输入时,我得到500,而不是404和错误消息找不到数据".谁能建议我在上面的代码中进行哪些更改?

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 ?

根据建议,我添加了以下课程:

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.

推荐答案

根据您的控制器,它用来引发"BusinessException"异常.但是您尚未实现在Controller Advisor中捕获该异常的方法"GlobalExceptionHandler".测试成功后,请在您的控制器顾问中包含以下方法.

As per your controller it uses to throw "BusinessException" exception. But you have not implemented a method to catch that exception in controller adviser which is "GlobalExceptionHandler ". Please include below method in your controller adviser as test was successful.

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

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

下面是测试结果

这篇关于在Spring Boot中无法从REST API返回错误代码和消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆