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,但无法修复此问题。有谁能帮我弄清楚我在这里遗漏了什么吗?谢谢
# 1 楼答案
为什么要扩展ResponseEntityExceptionHandler? @RestControllerAdvice将处理所有用@RestController注释的类。只需确保RestController和RestControllerAdvice注释的类都在SPRING扫描的包中
此外,如果您确实想扩展ResponseEntityExceptionHandler,以下文档可能会帮助您:
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/mvc/method/annotation/ResponseEntityExceptionHandler.html
# 2 楼答案
这是我的全球特长
这是错误信息。(我使用日期作为时间戳)
这是我抛出的一个例外
希望这有帮助:)