当我试图找出数据库中没有的值时,我得到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?
答案 0 :(得分:3)
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."))
<强>摘要强>
请勿在{{1}}上致电get()
而不检查它是否存在(使用Optional
方法)
答案 1 :(得分:1)
eventRepository.findById()
返回Optional
因此,您必须在get()
Optional<Event> optEvent = eventRepository.findById();
if (!optEvent.isPresent()) {
//throw exception here
}