gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:51:49 26 4
gpt4 key购买 nike

我编写了以下 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com