有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Spring中rest控制器返回错误消息和描述时出现java问题

我写了以下内容:

 @RestController
 @GetMapping(value = "/api", produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
 public ResponseEntity<?> getListOfPOWithItem(@QueryParam("input1") String input1,
                                        @QueryParam("input2") String input2)
                                   throws  EntityNotFoundException {

   List<Output> oList = myService.getOutput(input1, input2);
   if (oList != null) {
       return new ResponseEntity<List<Output>>(oList, HttpStatus.OK);
    }
}

和关联的异常处理程序,如下所示:

@RestControllerAdvice
@ApiIgnore
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

@ExceptionHandler(EntityNotFoundException.class)
public final ResponseEntity<ExceptionResponse> handleEntityNotFoundException(EntityNotFoundException ex,
  WebRequest request) {

  log(ex);

  ExceptionResponse exceptionResponse = new ExceptionResponse(Instant.now().toEpochMilli(),
    ex.getMessage(), request.getDescription(true));

  return new ResponseEntity<>(exceptionResponse, HttpStatus.NO_CONTENT);
}

除此之外,答复如下:

public class  ExceptionResponse {
 private long timestamp;
 private String message;
 private String details;

 public ExceptionResponse(long timestamp, String message, String details) 
{
 super();
 this.timestamp = timestamp;
 this.message = message;
 this.details = details;
}

public long getTimestamp() {
 return timestamp;
}

public String getMessage() {
 return message;
}

public String getDetails() {
 return details;
}

}

即使在那之后,在EntityNotFoundException的情况下,我只得到204条响应,没有错误消息或描述。我希望错误响应如下所示:

  {
     message : 
     {
                 timestamp:<>,
                 message:<>,
                 details:<>   
      }
  }

我已经从这篇文章获得了帮助:Not able to return error code with message from rest API in Spring boot,但无法修复此问题。有谁能帮我弄清楚我在这里遗漏了什么吗?谢谢


共 (2) 个答案

  1. # 1 楼答案

    为什么要扩展ResponseEntityExceptionHandler? @RestControllerAdvice将处理所有用@RestController注释的类。只需确保RestController和RestControllerAdvice注释的类都在SPRING扫描的包中

    此外,如果您确实想扩展ResponseEntityExceptionHandler,以下文档可能会帮助您:

    Note that in order for an @ControllerAdvice subclass to be detected, ExceptionHandlerExceptionResolver must be configured

    https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/mvc/method/annotation/ResponseEntityExceptionHandler.html

  2. # 2 楼答案

        @ControllerAdvice
    public class ExceptionHandle {
        @ExceptionHandler({ InvalidDataInputException.class, RelationNotFoundException.class,
                ActionIsInvalidException.class })
        public final ResponseEntity<ErrorMessage> handleSpecificExceptions(Exception ex, WebRequest request) {
            ErrorMessage errorMessage = new ErrorMessage(new Date(), ex.getMessage(), request.getDescription(false));
            return new ResponseEntity<>(errorMessage, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    
    }
    

    这是我的全球特长

       @Getter
    @Setter
    @NoArgsConstructor
    @AllArgsConstructor
    public class ErrorMessage {
        private Date timestamp;
        private String message;
        private String details;
    
    }
    

    这是错误信息。(我使用日期作为时间戳)

       public class InvalidDataInputException extends RuntimeException {
        public InvalidDataInputException(String message) {
            super(message);
        }
    }
    

    这是我抛出的一个例外

    if (retEmployee == null) {
                throw new InvalidDataInputException("Invalid data input");
            }
    

    希望这有帮助:)