我编写了以下 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
关于java - 从 Spring 中的其余 Controller 返回错误消息和描述的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56776545/