500 内部服务器错误,而不是 Spring 启动中的 404



当我尝试找出数据库中不存在的值时,出现 500 内部服务器错误。我已经提供了抛出ResourceNotFoundException错误的逻辑,但是,由于某种原因它不起作用。我需要做什么才能获得404 ResourceNotFoundException而不是500 Internal Server Error. 这是我的代码:

@PostMapping("/start/{id}")
public ResponseEntity<String> startEvent(@PathVariable() Long id) {
Event event = this.eventRepository.findById(id).get();
if (event == null) {
throw new ResourceNotFoundException("Event with id " + id + " not found.");
}
event.setStarted(true);
this.eventRepository.save(event);
return ResponseEntity.ok("Event " + event.getName() + " has started");
}

我猜 eventRepository.findById(id(//id = 200 返回 500 响应,因为数据库中不存在 id 为 200 的记录。我应该怎么做才能获得 ResourceNotFoundException?

eventRepository.findById返回Optional(在 Spring Data JPA 2.0.6 中,参见 https://docs.spring.io/spring-data/jpa/docs/2.0.6.RELEASE/reference/html/#repositories.core-concepts(

Optional.get空的可选原因NoSuchElementException(https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html#get--(。你的if (event == null)来得太晚了。 检查 stactrace,您应该看到异常来自this.eventRepository.findById行,实际异常NoSuchElementException

要解决此问题,您应该将代码更改为

Optional<Event> optionalEvent= this.eventRepository.findById(id);
if (!optionalEvent.isPresent()) {
throw new ResourceNotFoundException("Event with id " + id + " not found.");
}
Event event=optionalEvent.get();
//the rest of your logic

您也可以以更实用的方式编写代码

Event event = this.eventRepository
.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Event with id " + id + " not found."))

总结

不要在未检查Optional上调用get()是否存在(使用isPresent()方法(

eventRepository.findById()返回一个Optional因此,您必须在get()之前测试是否存在

Optional<Event> optEvent = eventRepository.findById();
if (!optEvent.isPresent()) {
//throw exception here   
}

最新更新