[英]Spring boot web app gives 500 internal server error instead 404 not found
[英]500 Internal Server Error instead of 404 in Spring Boot
当我尝试找出数据库中不存在的值时,出现500 Internal Server Error。 我已经提供了引发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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.