java - 从 Spring 中的其余 Controller 返回错误消息和描述的问题

标签 java spring

我编写了以下 Controller :

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

ExcetionResponse如下:

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 ,但无法解决这个问题。谁能帮我弄清楚我在这里缺少什么吗?谢谢。

最佳答案

为什么要扩展 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

关于java - 从 Spring 中的其余 Controller 返回错误消息和描述的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56776545/

相关文章:

java - Intellij 构建 scala 模块显示 scalac :Error:scala/xml/MetaData 错误

java - 我只想开始开发并花更少的时间处理依赖关系......是否有非 MVN 解决方案?

java - SpringBatch itemReader 使用大量内存

java - Swagger(-ui) 不显示操作

java - HttpClient 中的 setMaxTotal 和 setDefaultMaxPerRoute?

java - 我用这个 3x3 均值滤波器做错了什么?

java - 每次遇到字符时,在数组列表中拆分字符串

java - 速度显示不需要的字符

java - 使用 Spring MVC 在 jsp 文件中显示 XML

java - Spark异常: java. io.NotSerializedException : org. apache.spark.streaming.api.java.JavaStreamingContext