Spring@ExceptionHandler没有覆盖默认响应



我试图覆盖Spring Rest上Exceptions的默认响应,插入一个实体列表:

@RestController:

@ExceptionHandler(EntityConflictException.class)
public ResponseEntity<List<Entity>> exceptionHandler(EntityConflictException exception) {
return new ResponseEntity<>(exception.getList(), HttpStatus.CONFLICT);
}

异常:

@ResponseStatus(value = HttpStatus.CONFLICT)
public class EntityConflictException extends RuntimeException {
List<Entity> entities;
public EntityConflictException(List<Entity> entities) {
super("message");
this.entities = entities;
}
public EntityConflictException(String message) {
super(message);
}
public EntityConflictException(String message, Throwable cause) {
super(message, cause);
}
public List<Entity> getList() {
return entities;
}
}

在@服务上引发异常:

throw new EntityConflictException(entitiesList);

响应始终为:

{
"timestamp": "2021-03-27 20:15:36",
"status": 409,
"error": "Conflict",
"exception": "EntityConflictException",
"message": "Conflict",
"path": "/endpoint"
}

我认为您必须从EntityConflictException中删除@ResponseStatus(value = HttpStatus.CONFLICT)。它被注册为该Exception的defalut处理程序,并且不使用您的自定义异常处理方法。

看看这里的文章spring-boot异常处理,你就会明白,你使用的这两种异常处理方式并不意味着要一起使用。还指出,使用@ResponseStatus不能覆盖错误消息。

问题是我将hibernate实体传递给ResponseEntity。然后发生了典型的错误";未能延迟初始化";,但控制台上没有显示任何内容。我必须调试才能发现。

错误发生在第113行的Servlet InvocableHandlerMethod中

最新更新